1

For example, I know 0.1+0.2 == 0.3 is false because float number is not accurate sometimes. After adding toFixed(2) following Number.parseFloat, it becomes true:

console.log(0.1+0.2 == 0.3);
console.log(Number.parseFloat((0.1+0.2).toFixed(2))==0.3);

However, I want to know the general case of it: for float numbers x,y,z with 0-2 decimals (x,y may have different number of decimals, eg: 1.35+7.9),if x+y exactly equals to z in decimal form, and Number.MIN_VALUE <= x,y,z <= Number.MAX_VALUE, is

Number.parseFloat((x+y).toFixed(2))==z 

always true? If so, besides x+y, are x-y,x*y,x/y (without x/0) also implies in this case? If not, when would it be false?

2 Answers2

0

Analyzing Number.parseFloat((0.1+0.2).toFixed(2))==0.3

(0.1+0.2).toFixed(2) creates a string "0.30". parseFloat() scans the string and creates the number~0.299999999999999989 (printed by (0.30).toPrecision(18)). The number at the right is scanned by the parser and converted to the same number. So the result is true.

The rule is: Use formatting functions like toFixed() or toPrecision() only to generate output, but never for mathematical calculations.

If you need exact 1/100 (cents instead of dollar), then calculate in cents and use (num/100).toFixed(2) for the output. btw, banking software calculate very often in 0.00001 steps. So they print by (num/100000).toFixed(2).

Your question

Back to your question: Is Number.parseFloat((x+y).toFixed(2))==z always true (if z=x+y)?

Yes it is with exception of very large or very small numbers (precision issues).

Wiimm
  • 2,971
  • 1
  • 15
  • 25
0

No. For "float num with 0-2 decimals", which for this question is implied to be any rational number evenly divisable by 0.01 (since none of the given example numbers--0.1, 0.2, 0.3, 1.35, and 7.9--are exactly representable by a float), if x+y=z in decimal and MIN_VALUE<=x,y,z<=MAX_VALUE, Number.parseFloat((x+y).toFixed(2))==z is NOT always true. Here is the proof by contradiction:

                  1
 1234567890000000.37
+               1.03
--------------------
 1234567890000001.40

>
console.log(Number.parseFloat((1234567890000000.37+1.03).toFixed(2))==1234567890000001.40);
false
undefined
> 
Andrew
  • 1
  • 4
  • 19