1

In https://dartpad.dev/ I try:

void main() {
  print(double.parse('9223372036854775'));
}

It resulting 9223372036854776 instead of 9223372036854775

My question is:

  1. Why?

  2. If I need to limit the string by maxlength for accurate result, can I simply limit the text to 15 digits? Please tell me how you approach this problem.

Taufik Nur Rahmanda
  • 1,862
  • 2
  • 20
  • 36
  • Does this answer your question? [Why `uint64_t` cannot show `pow(2, 64) - 1` properly?](https://stackoverflow.com/q/54948430/995714). The question isn't about dart, but the same thing applies to any platform that uses IEEE-754 – phuclv Jan 18 '20 at 09:46
  • 1
    language agnostic duplicates: [Which is the first integer that an IEEE 754 float is incapable of representing exactly?](https://stackoverflow.com/q/3793838/995714), [Are all integer values perfectly represented as doubles?](https://stackoverflow.com/q/43655668/995714), [64-bit unsigned integers which cannot map onto a double](https://stackoverflow.com/q/17782425/995714) – phuclv Jan 18 '20 at 09:48
  • Thank you. Now I understand that double is tl;dr "innacurate", but my second question not yet answered. – Taufik Nur Rahmanda Jan 18 '20 at 09:49
  • 1
    depending on you want string→double→string round-trip conversion or double→string→double the answer will be 15 and 17 respectively: *"If a decimal string with at most 15 significant digits is converted to IEEE 754 double-precision representation, and then converted back to a decimal string with the same number of digits, the final result should match the original string. If an IEEE 754 double-precision number is converted to a decimal string with at least 17 significant digits, and then converted back to double-precision representation, the final result must match the original number"* – phuclv Jan 18 '20 at 09:57
  • 1
    the quote is from [wikipedia](https://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64) but it's too long for the comment. For more in-depth details read [17 Digits Gets You There, Once You’ve Found Your Way](https://www.exploringbinary.com/17-digits-gets-you-there-once-youve-found-your-way/), [Decimal Precision of Binary Floating-Point Numbers](https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/) – phuclv Jan 18 '20 at 09:58
  • My question already answered by @phuclv. I need to convert from string (e.g. from `TextFormField`'s controller) to double value, so exact match is in maximum 15 digits. I just have to give the `maxLength` of 15. Thank you very much for help. – Taufik Nur Rahmanda Jan 18 '20 at 10:04
  • And 15 digits is the optimal correct limit. The first *integer* which cannot be represented by a double is 9007199254740993, which has 16 digits. – lrn Jan 18 '20 at 13:50

0 Answers0