Dart double toStringAsFixed rounds the number, but it shouldn't
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
double x=43449716574226770.0;
print(x.toString());
Máté Antal
University student at Kecskemét, at GAMF, learning Software Development
Updated on January 01, 2023Comments
-
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 just43449716574226770
I have tried
.toInt().toString()
too, with the same results.The weirdest part is that it sometimes works, with other ids.
-
pskink over 2 yearsan id stored as a double?? why? if it is used as a string then store it as a string, not double
-
Máté Antal over 2 years@pskink If I convert it to string there, the same error applies..
-
pskink over 2 yearsyou 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 over 2 yearsIts not a string, it's a double from the API, sadly I can't change how the API gives it to me
-
jamesdlin over 2 yearsYour 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 anint
for more precision (on non-web platforms) or useBigInt
orString
for an arbitrary amount of precision.
-
-
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