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?
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 istrue.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))==zalways true (ifz=x+y)?Yes it is with exception of very large or very small numbers (precision issues).