Dart tryParse double vs string of double

Viewed 1616

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?

3 Answers

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".

10.0.toString() returns '10', not '10.0'. That's why you have different results. Here is just the same question. So, as I understand it, we have:

  • dart 10.0 parses as int on js target (and there is not such a big difference between int and double on js target, as said on the link);
  • dart 10.0 parses as double on dart VM, but toString returns the shortest possible text representation of that number, that is 10.

This seems to be a compiler behaviour. I can't find someone reporting this issue. Maybe when you have zeroes after the comma, the toString method will round it. If all zeroes after comma, then it will convert to int.

Related