I'm trying to parse a string value like this "2123123.12" using a portion of code like this
String stringAmount = "2123123.12";
float amount = Float.parseFloat(stringAmount);
But when I see the value have the next:
2123123.0
Have any idea.
Thanks in advance.
In
Java, float can only store 32bitnumbers. It stores numbers as 1bitfor the sign (-/+), 8bitsfor the Exponent, and 23bitsfor the fraction.Now, looking at your number and printint the decimal part,
System.out.println(Integer.toBinaryString(2123123));results in 23
bitwhich meansfloatdoes not have enough bits to store the fraction part and hence, it truncates the number.To store the whole number, you need to use
doublewhich is 64bitin Java, e.g.: