如何解决JavaScript舍入数最接近0.5
| 有人可以告诉我如何将数字四舍五入到最接近的0.5。 我必须根据屏幕分辨率缩放网页中的元素,为此,我只能将pts中的字体大小分配为1、1.5或2或更高版本,等等。 如果我四舍五入,则四舍五入到小数点后一位或无。 我怎样才能完成这项工作?解决方法
编写自己的函数,该函数先乘以2,再乘以2,然后除以2,例如
function roundHalf(num) {
return Math.round(num*2)/2;
}
,这是一个更通用的解决方案,可能对您有用:
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
,Math.round(-0.5)
返回0,但根据数学规则应为-1。
更多信息:Math.round()
和Number.prototype.toFixed()
function round(number) {
var value = (number * 2).toFixed() / 2;
return value;
}
, 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 );
,扩展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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。