【发布时间】:2011-09-02 12:55:36
【问题描述】:
有人可以告诉我如何将数字四舍五入到最接近的 0.5。
我必须根据屏幕分辨率缩放网页中的元素,为此我只能将 pts 中的字体大小分配为 1、1.5 或 2 等。
如果我四舍五入,则舍入到小数点后 1 位或无。 我怎样才能完成这项工作?
【问题讨论】:
标签: javascript
有人可以告诉我如何将数字四舍五入到最接近的 0.5。
我必须根据屏幕分辨率缩放网页中的元素,为此我只能将 pts 中的字体大小分配为 1、1.5 或 2 等。
如果我四舍五入,则舍入到小数点后 1 位或无。 我怎样才能完成这项工作?
【问题讨论】:
标签: javascript
编写自己的函数,乘以 2,四舍五入,然后除以 2,例如
function roundHalf(num) {
return Math.round(num*2)/2;
}
【讨论】:
roundHalf(15.27) 返回 15.5
var f = 2.6;
var v = Math.floor(f) + ( Math.round( (f - Math.floor(f)) ) ? 0.5 : 0.0 );
【讨论】:
Math.round(-0.5) 返回 0,但根据数学规则应该是 -1。
更多信息:Math.round() 和Number.prototype.toFixed()
function round(number) {
var value = (number * 2).toFixed() / 2;
return value;
}
【讨论】:
round 舍入到大于给定值的下一个整数,就负数而言,这将朝向正整数频谱。 -2.5 将变为 -2。对吗?
Math.ceil(-1.75) == -1 和 Math.floor(-1.75) == -2。所以对于任何被这个绊倒的人,只要把它想象成ceil返回一个大于的数字,floor返回一个小于的数字。
这里有一个更通用的解决方案,可能对您有用:
function round(value, step) {
step || (step = 1.0);
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
round(2.74, 0.1) = 2.7
round(2.74, 0.25) = 2.75
round(2.74, 0.5) = 2.5
round(2.74, 1.0) = 3.0
【讨论】:
inv 是什么意思? inv 变量代表什么?
inverse。
function roundToTheHalfDollar(inputValue){
var percentile = Math.round((Math.round(inputValue*Math.pow(10,2))/Math.pow(10,2)-parseFloat(Math.trunc(inputValue)))*100)
var outputValue = (0.5 * (percentile >= 25 ? 1 : 0)) + (0.5 * (percentile >= 75 ? 1 : 0))
return Math.trunc(inputValue) + outputValue
}
我在看到 Tunaki 更好的回应之前写了这篇文章 ;)
【讨论】:
将 newtron 的最佳答案扩展到仅 0.5 以上的四舍五入
function roundByNum(num, rounder) {
var multiplier = 1/(rounder||0.5);
return Math.round(num*multiplier)/multiplier;
}
console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76
【讨论】:
只是上述所有答案的精简版:
Math.round(valueToRound / 0.5) * 0.5;
通用:
Math.round(valueToRound / step) * step;
【讨论】:
作为上述好答案的一个更灵活的变体。
function roundNumber(value, step = 1.0, type = 'round') {
step || (step = 1.0);
const inv = 1.0 / step;
const mathFunc = 'ceil' === type ? Math.ceil : ('floor' === type ? Math.floor : Math.round);
return mathFunc(value * inv) / inv;
}
【讨论】: