Eric
Eric

Reputation: 6345

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. Where is last 5 (in the decimal) coming from? I would have expected it to return "123456789012345.120". I executed this code on Mac with an Intel processor using Chrome version 68.

Upvotes: 2

Views: 109

Answers (1)

psiphi75
psiphi75

Reputation: 2065

Your number is too long (has too many digits), it does not fit into the 64-bit floating point precision of a JavaScript number.

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.

It's not possible to represent the number you show using normal JavaScript numbers. You would need to implement something like bignumber.js.

If using bignumber.js then you can do the same using the following:

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'

Upvotes: 2

Related Questions