例如,我需要将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…我做错了什么?
当前回答
如果你不仅想在浮动上使用toFixed(),而且还想使用ceil()和floor(),那么你可以使用以下函数:
function roundUsing(func, number, prec) {
var tempnumber = number * Math.pow(10, prec);
tempnumber = func(tempnumber);
return tempnumber / Math.pow(10, prec);
}
生产:
> roundUsing(Math.floor, 0.99999999, 3)
0.999
> roundUsing(Math.ceil, 0.1111111, 3)
0.112
UPD:
另一种可能的方式是:
Number.prototype.roundUsing = function(func, prec){
var temp = this * Math.pow(10, prec)
temp = func(temp);
return temp / Math.pow(10, prec)
}
生产:
> 6.688689.roundUsing(Math.ceil, 1)
6.7
> 6.688689.roundUsing(Math.round, 1)
6.7
> 6.688689.roundUsing(Math.floor, 1)
6.6
其他回答
我认为下面的功能可以帮助
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
用法:roundOff(600.23458,2);会返回600.23吗
对这个答案的小调整:
function roundToStep(value, stepParam) {
var step = stepParam || 1.0;
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
roundToStep(2, 0.01) = 2
使用toFixed()函数。
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
我有很好的解决方案,如果toFixed()不工作。
function roundOff(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
例子
roundOff(10.456,2) //output 10.46
还有另一个. tolocalestring()来格式化数字,有很多关于地区、分组、货币格式和符号的选项。一些例子:
四舍五入到小数点后1,返回一个浮点数:
Const n = +6.688689。toLocaleString (fullwide, {maximumFractionDigits: 1}) console.log ( N类型的N )
四舍五入至2位小数,格式为带有指定符号的货币,千位使用逗号分组:
console.log ( 68766.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'currency', currency:'USD', useGrouping:true}) )
格式为区域货币:
console.log ( 68766.688689.toLocaleString('fr-FR', {maximumFractionDigits:2, style:'currency', currency:'EUR'}) )
四舍五入到最小3位小数,强制0显示:
游戏机。log ( 6.000000.toLocaleString(’fullwide’,(minimumFractionDigits: 3)) )
百分比风格的比率。输入* 100,带%符号
游戏机。log ( 6.688689.toLocaleString(' fullwed ') )