简体   繁体   English

为什么 JavaScript 在解析的数字末尾添加一个额外的非零数字

[英]Why is JavaScript adding an additional non zero number at the end of the parsed number

When I run, Number(123456789012345.12).toFixed(3) , it is returning "123456789012345.125" as a String.当我运行Number(123456789012345.12).toFixed(3) ,它以字符串形式返回"123456789012345.125" Where is last 5 (in the decimal) coming from?最后 5(十进制)来自哪里? I would have expected it to return "123456789012345.120" .我原以为它会返回"123456789012345.120" I executed this code on Mac with an Intel processor using Chrome version 68.我使用 Chrome 68 版在带有 Intel 处理器的 Mac 上执行了此代码。

Your number is too long (has too many digits), it does not fit into the 64-bit floating point precision of a JavaScript number.您的数字太长(位数太多),它不符合 JavaScript 数字的64 位浮点精度。

Below is an example of using less digits:以下是使用较少数字的示例:

Number(123456789012345.12).toFixed(3):  '123456789012345.125'
Number(12345678901234.12).toFixed(3):    '12345678901234.119'
Number(1234567890123.12).toFixed(3):      '1234567890123.120'
Number(123456789012.12).toFixed(3):        '123456789012.120'
Number(12345678901.12).toFixed(3):          '12345678901.120'

JavaScript numbers are represented by a 64-bit floating point value. JavaScript 数字由 64 位浮点值表示。

It's not possible to represent the number you show using normal JavaScript numbers.使用普通 JavaScript 数字无法表示您显示的数字。 You would need to implement something like bignumber.js .你需要实现类似bignumber.js 的东西。

If using bignumber.js then you can do the same using the following:如果使用 bignumber.js 那么您可以使用以下内容执行相同操作:

let BigNumber = require('bignumber.js');
BigNumber('123456789012345.12').toFixed(3):  '123456789012345.120'
BigNumber('12345678901234.12').toFixed(3):    '12345678901234.120'
BigNumber('1234567890123.12').toFixed(3):      '1234567890123.120'
BigNumber('123456789012.12').toFixed(3):        '123456789012.120'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM