我希望将数字限制为小数点后两位,但仅当其余部分为零时。我不想四舍五入这些数字。
我试过使用这个例子
(1.0000).toFixed(2)
结果将是 1.00,但如果我有一个像 (1.0030).toFixed(2)
这样的数字,结果应该是 1.003。
我尝试将 parseFloat 与 toFixed 组合使用,但没有得到我想要的结果。
javascript 中是否有任何函数可以实现我想要实现的目标。
最佳答案
所以你想要最少两位小数?这是一种方法:
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
return num == num.toFixed(2) ? num.toFixed(2) : num.toString();
}
例子:
toMinTwoDecimals("1.0030"); // returns "1.003"
toMinTwoDecimals("1.0000"); // returns "1.00"
toMinTwoDecimals("1"); // returns "1.00"
toMinTwoDecimals("-5.24342234"); // returns "-5.24342234"
如果您想保留少于两位小数的数字,请改用:
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
// Trim extra zeros for numbers with three or more
// significant decimals (e.g. "1.0030" => "1.003")
if (num != num.toFixed(2)) {
return num.toString();
}
// Leave numbers with zero or one decimal untouched
// (e.g. "5", "1.3")
if (numString === num.toFixed(0) || numString === num.toFixed(1)) {
return numString;
}
// Limit to two decimals for numbers with extra zeros
// (e.g. "1.0000" => "1.00", "1.1000000" => "1.10")
return num.toFixed(2);
}
关于javascript - 将小数点限制在特定情况下(不是四舍五入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978911/