例如,我需要将6.688689舍入到6.7,但它总是显示7。
我的方法:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
但结果总是一样的7…我做错了什么?
例如,我需要将6.688689舍入到6.7,但它总是显示7。
我的方法:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
但结果总是一样的7…我做错了什么?
当前回答
Math.round((6.688689 + Number.EPSILON) * 10) / 10
解决方案被盗自https://stackoverflow.com/a/11832950/2443681
这应该适用于几乎任何浮点值。它不强制十进制计数。目前尚不清楚这是否是一项要求。应该比使用toFixed()更快,根据对其他答案的注释,它也有其他问题。
一个很好的实用函数来四舍五入所需的十进制精度:
const roundToPrecision = (value, decimals) => {
const pow = Math.pow(10, decimals);
return Math.round((value + Number.EPSILON) * pow) / pow;
};
其他回答
如果你在node.js环境下,你可以尝试mathjs
const math = require('mathjs')
math.round(3.1415926, 2)
// result: 3.14
如果你现在正在使用Browserify,你将不得不尝试:roundTo一个非常有用的NPM库
见下文
原始变量 = 28.59;
var result=Math.round(原*10)/10将返回28.6
希望这就是你想要的。
我认为这个函数会有帮助。
function round(value, ndec){
var n = 10;
for(var i = 1; i < ndec; i++){
n *=10;
}
if(!ndec || ndec <= 0)
return Math.round(value);
else
return Math.round(value * n) / n;
}
round(2.245, 2) //2.25
round(2.245, 0) //2
Math.round((6.688689 + Number.EPSILON) * 10) / 10
解决方案被盗自https://stackoverflow.com/a/11832950/2443681
这应该适用于几乎任何浮点值。它不强制十进制计数。目前尚不清楚这是否是一项要求。应该比使用toFixed()更快,根据对其他答案的注释,它也有其他问题。
一个很好的实用函数来四舍五入所需的十进制精度:
const roundToPrecision = (value, decimals) => {
const pow = Math.pow(10, decimals);
return Math.round((value + Number.EPSILON) * pow) / pow;
};