-1

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.

divibisan
  • 11,659
  • 11
  • 40
  • 58
csuazo
  • 164
  • 3
  • 20
  • 2
    Don't use `float`. It cannot store that many digits of precision ([only 6-9](https://en.wikipedia.org/wiki/Single-precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32)). Use `double` for more precision ([15–17](https://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64)), but for values like amounts, you should [use `BigDecimal`](http://stackoverflow.com/q/6320209/5221149). – Andreas Mar 24 '17 at 21:07

1 Answers1

1

In Java, float can only store 32 bit numbers. It stores numbers as 1 bit for the sign (-/+), 8 bits for the Exponent, and 23 bits for the fraction.

Now, looking at your number and printint the decimal part,

System.out.println(Integer.toBinaryString(2123123));

results in 23 bit which means float does not have enough bits to store the fraction part and hence, it truncates the number.

To store the whole number, you need to use double which is 64 bit in Java, e.g.:

String stringAmount = "2123123.12";
double amount = Double.parseDouble(stringAmount);
System.out.println(amount);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102