0

Accrodading to Is floating point math broken?, I know 0.1+0.2 results in 0.30000000000000004 instead of 0.3 because of floating point errors. However, what if I copy "0.30000000000000004" from alert(0.1+0.2) and write Number("0.30000000000000004"), would it still equal to 0.1+0.2?

Or in general:

let a=float_number_1 + float_number2;
let b=Number((float_number_1 + float_number2).toString());

Does a always exactly equal to b?

aacceeggiikk
  • 101
  • 1
  • `console.log(Number("0.30000000000000004") === 0.1+0.2)` – epascarello Feb 06 '20 at 03:46
  • For the cases you think of, yes. The only case that comes to mind, where this fails, is `NaN !== Number("NaN")`. – ASDFGerte Feb 06 '20 at 03:48
  • @epascarello—I think the OP is looking at the general case, not that special case. – RobG Feb 06 '20 at 03:50
  • Seems like a simple, albeit time-consuming, thing to test. – Heretic Monkey Feb 06 '20 at 03:53
  • Btw depending on how you define "equal", `-0` should be the only other edge case (`-0 === 0`, and `NaN !== NaN`, but `Object.is(-0, 0) === false`, and `Object.is(NaN, NaN) === true`). I could go into details about how conversion from number to string and back works, but it's late, i am tired, and the spec has a nice note about this: "If x is any Number value other than -0, then ToNumber(ToString(x)) is exactly the same Number value as x.", in the notes below [Number::toString](https://tc39.es/ecma262/#sec-numeric-types-number-tostring). Note, that being tired, i can always make mistakes. – ASDFGerte Feb 06 '20 at 04:23

1 Answers1

1

Java’s default conversion of a number to a string is specified to produce enough digits to uniquely distinguish the number from adjacent representable values. In other words, it is deliberately designed to produce a string that can be converted back to a number to produce the original value.

So, if you convert from a float to a string to a float or from a double to a string to a double, you will get the original number. If you convert a double to a string to a float, you may get a different number.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312