https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Shalom Halbert

01/22/2022, 9:41 PM
Is it possible convert
Int.MAX_VALUE
to a
Double
? I’ve tried
toDouble()
, but that outputs 2.147483647E9
e

ephemient

01/22/2022, 10:32 PM
Int.MAX_VALUE.toDouble()
is exact, you're just seeing
Double.toString()
truncating to 9 digits of precision by default
Copy code
"%.10g".format(Int.MAX_VALUE.toDouble())
will show 10 digits of precision, which is enough for all digits of
Int.MAX_VALUE
s

Shalom Halbert

01/22/2022, 10:57 PM
So the reason
Int.MAX_VALUE.toDouble()
equals 2.147483647E9 instead of 2147483647.0 is because that requires 11 digits? That’s confusing because the Kotlin docs say there can be “15-16” decimal digits. To clarify the situation, below are the cases referenced so far.
Copy code
Int.MAX_VALUE // 2147483647
Int.MAX_VALUE.toDouble() // 2.147483647E9
"%.10g".format(Int.MAX_VALUE.toDouble()) // "2147483647"
e

ephemient

01/22/2022, 11:00 PM
Int.MAX_VALUE.toDouble()
does not equal 2.147483647E9, that is just its string representation
most Doubles have string representations that do not parse back to the same Double
j

Joffrey

01/22/2022, 11:53 PM
equals 2.147483647E9 instead of 2147483647.0
@Shalom Halbert both of these are the same number. The first one is simply written in scientific notation (with E9 at the end meaning x10^9), while the other is in standard notation. It's just a matter of how you print the string representation of the number, as @ephemient pointed out. What is your issue with this output exactly? Is it because of the scientific notation, or is it because you believe the value is not the same?
e

ephemient

01/22/2022, 11:57 PM
actually I was mistaken to a certain extent; it is supposed to emit the shortest string that can uniquely reproduce the same Double. but (at least on JVM) it's buggy: https://bugs.openjdk.java.net/browse/JDK-4511638
in any case you're not running into that here, it's simply a different representation than you may be expecting, but it is still the same Double
s

Shalom Halbert

01/23/2022, 12:27 AM
You folks have it correct, I didn't realize that
toDouble()
converts the
Int
into the same number, using scientific notation. Thank you for helping me realize that I was reading it wrong
j

Joffrey

01/23/2022, 12:31 AM
Just to be 100% clear, the conversion done by
Int.toDouble()
is format-agnostic, it converts the int value into the same value of type
Double
. The scientific notation only matters (or even exists) when you try to print the number
1
e

ephemient

01/23/2022, 12:57 AM
Copy code
int.toDouble().toInt() == int // for all Int, but not all Long
double.toString().toDouble() == double // except NaN
j

Joffrey

01/23/2022, 1:00 AM
I meant
Int.toDouble()
, of course when strings are involved it's all about format
26 Views