在JavaScript中,将浮点数转换为字符串时,如何仅获取小数点后两位?例如,获取0.34而不是0.3445434。
var x = 5.036432346; var y = x.toFixed(2) + 100;
y
将等于"5.03100"
。 - Vlad(0.335).toFixed(2) == 0.34 == (0.345).toFixed(2)
... - Skippy le Grand GouroutoFixed()
会模仿C语言中的printf()
函数。然而,toFixed()
和Math.round()
会以不同的方式处理四舍五入。在这种情况下,如果你事先将原始数字乘以10^n,然后使用n个数字调用toFixed()
,那么toFixed()
将具有与Math.floor()
相同的效果。答案的“正确性”非常依赖于OP在这里想要什么,两者在其自己的方式上都是“正确”的。 - DDPWNAGE使用toFixed()
时要小心:
首先,四舍五入是使用数字的二进制表示来完成的,这可能会导致意外行为。例如:
(0.595).toFixed(2) === '0.59'
使用'0.6'
替代。
其次,toFixed()
在IE中存在一个bug。在IE(至少到版本7,没有检查IE8),以下内容是正确的:
(0.9).toFixed(0) === '0'
你可以考虑采纳kkyy的建议或使用自定义的toFixed()
函数,例如:
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(value * power) / power);
}
.toFixed()
方法,这将增加所需的精度,例如:return (Math.round(value * power) / power).toFixed(precision);
,并将值作为字符串返回。否则,对于较小的小数,精度20会被忽略。 - William Joss CrowcrofttoFixed
的一个注意事项:请注意,增加精度可能会产生意外的结果:(1.2).toFixed(16) === "1.2000000000000000"
,而 (1.2).toFixed(17) === "1.19999999999999996"
(在 Firefox/Chrome 中;在 IE8 中,由于 IE8 内部可以提供较低的精度,后者不成立)。 - jakub.g(0.598).toFixed(2)
也不会产生0.6
,它会产生0.60
:) - qbolec(0.335).toFixed(2) == 0.34 == (0.345).toFixed(2)
。 - Skippy le Grand Gourou还需要注意的一个问题是,toFixed()
方法可能会在数字结尾处产生不必要的零。
var x=(23-7.37)
x
15.629999999999999
x.toFixed(6)
"15.630000"
这个想法是使用 RegExp
来清理输出:
function humanize(x){
return x.toFixed(6).replace(/\.?0*$/,'');
}
RegExp
匹配尾部的零(以及可选的小数点),以确保整数看起来合适。
humanize(23-7.37)
"15.63"
humanize(1200)
"1200"
humanize(1200.03)
"1200.03"
humanize(3/4)
"0.75"
humanize(4/3)
"1.333333"
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding
这里的关键是正确地四舍五入,然后再将其转换为字符串。
function roundOf(n, p) {
const n1 = n * Math.pow(10, p + 1);
const n2 = Math.floor(n1 / 10);
if (n1 >= (n2 * 10 + 5)) {
return (n2 + 1) / Math.pow(10, p);
}
return n2 / Math.pow(10, p);
}
// All edge cases listed in this thread
roundOf(95.345, 2); // 95.35
roundOf(95.344, 2); // 95.34
roundOf(5.0364342423, 2); // 5.04
roundOf(0.595, 2); // 0.60
roundOf(0.335, 2); // 0.34
roundOf(0.345, 2); // 0.35
roundOf(551.175, 2); // 551.18
roundOf(0.3445434, 2); // 0.34
roundOf(0.3445434, 2).toFixed(2); // 0.34
使用乘数的所有解决方案都存在问题。很遗憾,kkyy和Christoph的解决方案都是错误的。
请针对数字551.175进行测试,并保留2位小数——它会四舍五入为551.17,但应该是551.18!但是,如果您测试的是451.175等数字,则没有问题——451.18。因此,这个错误很难一眼就发现。
问题出在乘法上:尝试 551.175 * 100 = 55117.49999999999 (哎呀!)
所以我的想法是,在使用Math.round()之前使用toFixed()来处理它。
function roundFix(number, precision)
{
var multi = Math.pow(10, precision);
return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}
toFixed
也受到影响 - (0.335).toFixed(2) == 0.34 == (0.345).toFixed(2)
... 无论使用哪种方法,在舍入之前最好添加一个 epsilon。 - Skippy le Grand Gourou如果您想要不带括号的字符串,可以使用以下正则表达式(可能不是最有效的方法...但非常简单)
(2.34567778).toString().match(/\d+\.\d{2}/)[0]
// '2.34'
toLocaleString()
函数:
toLocaleString()
方法返回一个具有语言敏感性的该数字的字符串表示。
const n = 2048.345;
const str = n.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
console.log(str);
function trimNumber(num, len) {
const modulu_one = 1;
const start_numbers_float=2;
var int_part = Math.trunc(num);
var float_part = String(num % modulu_one);
float_part = float_part.slice(start_numbers_float, start_numbers_float+len);
return int_part+'.'+float_part;
}
return float_part ? int_part+'.'+float_part : int_part;
,否则如果输入整数,则返回带有结束符号的数字(例如输入:“2100”,输出:“2100.”)。 - Kuba Šimonovský