I
I
IvanVvV2018-03-22 12:07:54
JavaScript
IvanVvV, 2018-03-22 12:07:54

Why does toFixed round up like that?

0.755.toFixed(2); // result 0.76
0.7555.toFixed(3); // result 0.755
0.75555.toFixed(4); // result 0.7556
0.755555.toFixed(5); // result 0.75555
0.7555555.toFixed(6); // result 0.755556
0.75555555.toFixed(7); // result 0.7555555
Why is this happening, because in these examples there should always be a 6 at the end.?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lynn "Coffee Man", 2018-03-22
@IvanVvV

https://learn.javascript.ru/number#%D0%BD%D0%B5%D1...
Because these numbers cannot be represented exactly in double format (see IEEE 754)

> 0.755.toFixed(20)
'0.75500000000000000444'
> 0.7555.toFixed(20)
'0.75549999999999994937'
> 0.75555.toFixed(20)
'0.75555000000000005489'

Those. when you write 0.755 in computer representation it is actually a little more than 0.755 , and for 0.7555 it 's a little less.

D
Denis, 2018-03-22
@sidni

it was mine
JS - how to leave only 2 decimal places (not round) after the decimal point?
respectively, how many numbers should be left after the decimal point by this order to multiply and then divide

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question