Dart double toStringAsFixed rounds the number, but it shouldn't

235

Solution 1

This number as long would be in a 6-byte range? As double this with an exponent part, this might mean that the previous double (bit wise) would have a difference more than 1. Also see java Math.ulp.

This implies that using a double instead of a long maps some double IDs to the same "long" ID.

I am not sure this is the problem here, but it would explain a deviation of 2.

Solution 2

enter image description hereCan you please try this

double x=43449716574226770.0;
print(x.toString());
Share:
235
Máté Antal
Author by

Máté Antal

University student at Kecskemét, at GAMF, learning Software Development

Updated on January 01, 2023

Comments

  • Máté Antal
    Máté Antal over 1 year

    I have a Flutter project, in SharedPrefs, I'm storing a double id, from a Third-part API. (so I can only get it as a double)

    The id from prefs is 43449716574226770.0

    I have to parse this double to a String, I'm doing it like this:

    String idString = id.toStringAsFixed(0)  
    

    What I'm getting is somehow: 43449716574226768 but I'd like it to be just 43449716574226770

    I have tried .toInt().toString() too, with the same results.

    The weirdest part is that it sometimes works, with other ids.

    • pskink
      pskink over 2 years
      an id stored as a double?? why? if it is used as a string then store it as a string, not double
    • Máté Antal
      Máté Antal over 2 years
      @pskink If I convert it to string there, the same error applies..
    • pskink
      pskink over 2 years
      you dont need to convert string to string - keep it in SharedPrefs as a string and you will not need to convert anything
    • Máté Antal
      Máté Antal over 2 years
      Its not a string, it's a double from the API, sadly I can't change how the API gives it to me
    • jamesdlin
      jamesdlin over 2 years
      Your number is too large to be exactly representable by the 53 bits of precision for a double's significand. Low bits therefore will get discarded. Use an int for more precision (on non-web platforms) or use BigInt or String for an arbitrary amount of precision.
  • Máté Antal
    Máté Antal over 2 years
    .round() would not work for us, if the end of the number is 771.0 it rounds it to 770