D
D
d_fly2015-10-19 19:32:54
JavaScript
d_fly, 2015-10-19 19:32:54

How does the .toFixed() function work in javaScript?

On work it is necessary to understand with javaScript. There is a .toFixed(2) function that rounds a number to 2 decimal places. The question is - how does she do it when we have 3 decimal places - 5? (for example, 0.915, 1.235, etc.)

1) At first I thought that it was a simple rounding up. Ie:
0.915 -> should have gone to 0.92
Check:
- 0.905.toFixed(2) = 0.91 - ok
- 0.915.toFixed(2) = 0.92 - ok
- 0.925.toFixed(2) = 0.93 - ok
.. ...
- 0.955.toFixed(2) = 0.96 - false! JavaScript says = 0.95!
- 0.965.toFixed(2) = 0.97 - false! JavaScript says = 0.96!
So. Rounding up is not appropriate.

2) Apparently the function works as follows: from 0.905 to 0.945 we increase upwards, and from 0.955 to 0.995 we simply discard 5.
Check:
- 0.905.toFixed(2) = 0.91 - ok
- 0.915.toFixed(2) = 0.92 - ok
- 0.925.toFixed(2) = 0.93 - ok
....
- 0.955.toFixed(2) = 0.95 - ok
- 0.995.toFixed(2) = 0.99 - ok

And everything was fine until I checked for this value:
- 0.755.toFixed(2) = 0.75 - false! JavaScript says = 0.76!
- 0.765.toFixed(2) = 0.76 - false! JavaScript says = 0.77!

I thought maybe it's not even parity 7-ki? So this is the result. But here I broke down completely:
- 1.755.toFixed(2) = 1.76 - false! (According to the previous example) BUT! JavaScript says = 1.75!

Hence the question - what is the algorithm of the .toFixed() method?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aves, 2015-10-19
@Aves

It rounds according to the usual rules, but is inaccurate due to floating point operations in binary format - blog.chewxy.com/2014/02/24/what-every-javascript-d...
Round exactly like this:Math.round(0.955*100)/100

S
Stalker_RED, 2015-10-19
@Stalker_RED

>> How it works It
sucks, it works. If you want precision - use Math.Round()
Demo: jsfiddle.net/Stalk/5spu017s/1

D
Dasha Tsiklauri, 2015-10-19
@dasha_programmist

She doesn't round anything! rounds math.round()
read documentation https://developer.mozilla.org/en-US/docs/Web/JavaS...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question