Reputation: 3507
I have a question regarding below code, where if we use the Float.toString()
method it will do some rounding of digits. Why does it do this? Is there any specific logic behind that?
I have also looked at the internal code of Float.toString()
. It's calling FloatingDecimal(f).toJavaFormatString()
.
public static void main(String[] args) {
Float f = Float.intBitsToFloat(1342177280);
String simpleString = new BigDecimal(f).toPlainString();
System.out.println("simpleString value " + simpleString);
String withToString = new BigDecimal(Float.toString(f)).toPlainString();
System.out.println("withToString value " + withToString);
}
Output is like this
simpleString value 8589934592
withToString value 8589934600 //here value changed
Upvotes: 2
Views: 123
Reputation: 14572
The BigDecimal constructor is simple. Give me a String, I will create a number with it. If you give me a number, I will use his value directly.
Since the String generate in your example looks like 8.5899346E9
, the value in plain number is 8589934600
. If you send the float instance, it will (i guess) works with the bits to recreate the value as precisly as possible.
Upvotes: 1