例如,我需要将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…我做错了什么?
当前回答
如果你在node.js环境下,你可以尝试mathjs
const math = require('mathjs')
math.round(3.1415926, 2)
// result: 3.14
其他回答
使用toFixed()函数。
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
我的扩展圆函数:
function round(value, precision) {
if (Number.isInteger(precision)) {
var shift = Math.pow(10, precision);
// Limited preventing decimal issue
return (Math.round( value * shift + 0.00000000000001 ) / shift);
} else {
return Math.round(value);
}
}
示例输出:
round(123.688689) // 123
round(123.688689, 0) // 123
round(123.688689, 1) // 123.7
round(123.688689, 2) // 123.69
round(123.688689, -2) // 100
round(1.015, 2) // 1.02
见下文
原始变量 = 28.59;
var result=Math.round(原*10)/10将返回28.6
希望这就是你想要的。
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
还有另一个. 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 ') )