javascript浮点值问题,精度浮点数超过6位

时间:2016-11-17 08:20:31

标签: javascript floating-point

这里我对javascript浮动值感到震惊,我需要显示浮点数的实际值,最多8位小数,但是brower的JS引擎将值转换为0.00000001到1e-8。

function toCustomString(numberToFormat) {
            return '' + Number(numberToFormat.toFixed(8).replace(/\,/g, ','));
        };

// Floating value with 6 digits
var value1 = 0.000001;
console.log(toCustomString(value1))


// Floating value with 8 digits
var value2 = 0.00000001;
console.log(toCustomString(value2) + " <-- this is wrong") // I want here output should be 0.00000001

// Floating value with 8 digits but value greate than 0.000001
var value3 = 0.00010000;
console.log(toCustomString(value3))

1 个答案:

答案 0 :(得分:0)

如果您想完全控制digits,请查看https://github.com/MikeMcl/decimal.js

如果您不想尾随0,请使用正则表达式删除它们:

console.log(
  '"trailing 0":',
  Number("0.00010000").toFixed(8)
);
console.log(
  '"no trailing 0":',
  Number("0.00010000").toFixed(8).replace(/0*$/,'')
);

使用0.0000000001

console.log(
  '"trailing 0":',
  Number("0.0000000001").toFixed(8)
);
console.log(
  '"no trailing 0":',
  Number("0.0000000001").toFixed(8).replace(/0*$/,'')
);