在JavaScript中,当从浮点数转换为字符串时,如何才能在小数点后得到2位数字?例如,0.34而不是0.3445434。


当前回答

var result = Math.round(original*100)/100;

具体细节,以防代码不是自解释的。

编辑:…或者直接使用toFixed,就像Tim Büthe提议的那样。忘记了,谢谢你的提醒(还有点赞):)

其他回答

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;
}

There is no way to avoid inconsistent rounding for prices with x.xx5 as actual value using either multiplication or division. If you need to calculate correct prices client-side you should keep all amounts in cents. This is due to the nature of the internal representation of numeric values in JavaScript. Notice that Excel suffers from the same problems so most people wouldn't notice the small errors caused by this phenomen. However errors may accumulate whenever you add up a lot of calculated values, there is a whole theory around this involving the order of calculations and other methods to minimize the error in the final result. To emphasize on the problems with decimal values, please note that 0.1 + 0.2 is not exactly equal to 0.3 in JavaScript, while 1 + 2 is equal to 3.

有一些函数可以取整数字。例如:

var x = 5.0364342423;
print(x.toFixed(2));

将打印5.04。

编辑: 小提琴

使用toFixed()时要小心:

首先,使用数字的二进制表示来四舍五入,这可能会导致意想不到的行为。例如

(0.595).toFixed(2) === '0.59'

而不是‘0.6’。

其次,toFixed()存在IE错误。在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()会在数字末尾产生不必要的零。 例如:

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"