Search code examples
stringparsingdartdouble

Dart tryParse double vs string of double


There seems to be some inconsistency with the way tryParse is used in Dart or I'm going about it a silly way, likely the latter.

When we use the int.tryParse statement, if we pass it 10.0 as a double, we would expect to get 10 which we do.

print(int.tryParse(10.0.toString())); ==> 10

If we pass it 10.0 as a string, it will return null.

print(int.tryParse('10.0')); ==> null

I find this a bit strange as I would have thought 10.0.toString() is equivalent to '10.0'. Does anyone have an explanation?


Solution

  • The difference is between web compiler and native code.

    When Dart is compiled to the web (to JavaScript), all numbers are JavaScript numbers, which effectively means doubles. That means that the integer 10 and the double 10.0 is the same object. There is only on "10" value in JavaScript. So, when you do toString on that value, it has to choose, and it chooses "10" over "10.0".

    When run natively, the double 10.0 and the integer 10 are two different objects, and their toStrings are "10.0" and "10" respectively.

    The int.tryParse function does not accept "10.0" as input, which is why it returns null. So, when testing on the web (including dartpad.dev), int.tryParse(10.0.toString()) succeeds because the toString is "10", and when testing natively the same code gives null because the toString is "10.0".