有人可以告诉我如何将数字四舍五入到最接近的0.5。
我必须根据屏幕分辨率缩放网页中的元素,为此,我只能将pts中的字体大小分配为1、1.5或2或更高版本,等等。
如果我四舍五入,则四舍五入到小数点后一位或无。我怎样才能完成这项工作?
Answers:
编写自己的函数,该函数乘以2,四舍五入,然后除以2,例如
function roundHalf(num) {
return Math.round(num*2)/2;
}
roundHalf(15.27)收益15.5
这是一个更通用的解决方案,可能对您有用:
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。
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返回的小于数字即可。
扩展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
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更好的响应之前;)
var f = 2.6;
var v = Math.floor(f) + ( Math.round( (f - Math.floor(f)) ) ? 0.5 : 0.0 );