Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript toFixed() is not working as expected

Tags:

javascript

I am using toFixed but the method does not operate as expected

parseFloat(19373.315).toFixed(2);

//19373.31   Chrome 

Expected Output : 19373.32

parseFloat(9373.315).toFixed(2);
// 9373.32  Working fine

Why does the first example round down, whereas the second example round up?

like image 271
Hitu Bansal Avatar asked Mar 27 '26 22:03

Hitu Bansal


2 Answers

The problem is that binary floating point representation of most decimal fractions is not exact. The internal representation of 19373.315 may actually be something like 19373.314999999, so toFixed rounds down, while 19373.315 might be 19373.315000001, which rounds up.

like image 172
Vahid Rahmani Avatar answered Mar 31 '26 03:03

Vahid Rahmani


Why does the first example round down, whereas the second example round up?

Look at the binary representation of the two values in memory.

const farr = new Float64Array(2);
farr[0] = 19373.315;
farr[1] = 9373.315;
const uarr = new Uint32Array(farr.buffer);
console.log(farr[0], uarr[1].toString(2).padStart(32, 0) + uarr[0].toString(2).padStart(32, 0));
console.log(farr[1], uarr[3].toString(2).padStart(32, 0) + uarr[2].toString(2).padStart(32, 0));

Without diving into the details, we can see that the second value has an additional '1' at the end, which is lost in the first larger value when it is fit into 64 bits.

like image 29
GOTO 0 Avatar answered Mar 31 '26 05:03

GOTO 0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!