JavaScript中的2个小数,没有正则表达式,没有四舍五入

2 decimals in JavaScript with out regular expression and without rounding the numbers

本文关键字:正则表达式 四舍五入 中的 2个 JavaScript 小数      更新时间:2023-09-26

谁能给我使用JavaScript只接受2个小数的代码?不含正则表达式,不含jQuery。数字不能四舍五入

To Fixed

使用toFixed(2);

var num = 2.4;
alert(num.toFixed(2));  will alert 2.40

Try with

parseFloat(Math.round(yourNum * 100) / 100).toFixed(2);

试试这个

 Math.round(num * 100) / 100

数字不能四舍五入

使用Math.floor来舍入,您可以使用Math.pow来一般设置位数。

function trimDP(x, i) {
    var e = Math.pow(10, i || 0);
    return Math.floor(e * x) / e;
}
trimDP(2.45991, 2); // 2.45

如果你想把它作为字符串,你需要在之后使用.toFixed(i) ,这样它就不会被舍入。

var x = trimDP(2.40001, 2); // 2.4
x.toString(2); // "2.40"