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


当前回答

我使用这段代码来格式化浮动。它基于toPrecision(),但它去掉了不必要的零。我欢迎关于如何简化正则表达式的建议。

function round(x, n) {
    var exp = Math.pow(10, n);
    return Math.floor(x*exp + 0.5)/exp;
}

使用的例子:

function test(x, n, d) {
    var rounded = rnd(x, d);
    var result = rounded.toPrecision(n);
    result = result.replace(/\.?0*$/, '');
    result = result.replace(/\.?0*e/, 'e');
    result = result.replace('e+', 'e');
    return result;  
}

document.write(test(1.2000e45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2000e+45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2340e45, 3, 2) + '=' + '1.23e45' + '<br>');
document.write(test(1.2350e45, 3, 2) + '=' + '1.24e45' + '<br>');
document.write(test(1.0000, 3, 2) + '=' + '1' + '<br>');
document.write(test(1.0100, 3, 2) + '=' + '1.01' + '<br>');
document.write(test(1.2340, 4, 2) + '=' + '1.23' + '<br>');
document.write(test(1.2350, 4, 2) + '=' + '1.24' + '<br>');

其他回答

var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

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.

如果你想要不带圆的字符串,你可以使用这个RegEx(可能不是最有效的方法…但是真的很简单)

(2.34567778).toString().match(/\d+\.\d{2}/)[0]
// '2.34'

使用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);
}
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;
}