From the discussion here and here we see that toFixed()
can be used to help maintain precision when working with binary floats.
For various reasons, I do not want to use a third party library. However, for any fraction that can be expressed as a finite decimal within 64 bits, I would like to maintain maximum precision in the most generic way possible.
Assuming I use toFixed()
, when do I need to use it? And is there a single "best" argument that I can pass to it to achieve the above goal?
For example, consider JavaScript's ability to represent the fraction 1/10 as a finite decimal after different operations:
10/100 = 0.1
0.09 + 0.01 = 0.09999999999999999
1.1 - 1 = 0.10000000000000009
The first requires no correction step while the last two do. Furthermore passing toFixed()
a value of 15 works in this case (ex: Number((0.09 + 0.01).toFixed(15))
):
10/100 = 0.1
0.09 + 0.01 = 0.1
1.1 - 1 = 0.1
but passing 16 does not:
10/100 = 0.1
0.09 + 0.01 = 0.1
1.1 - 1 = 0.1000000000000001
Try JSFIDDLE.
Will 15 as the argument for toFixed()
always achieve the above objective? More importantly, when do I have to call toFixed()
? In addition to add, subtract, multiply and divide, my math routines use Math.pow()
, Math.exp()
and Math.log()
.