Search code examples
javastringfloating-point-conversion

Float to string conversion output differs


I am trying to parse string to float but it gives me some different output. Suppose my code :

String a = "111111111111111111111.23";
Float f = Float.parseFloat(a);
System.out.println(f);

It gives me something like: 1.1111111E20

In a simple manner, it gives me 111111110000000000000

How do I get all the data shown? I do not want to truncate the input data.


Solution

  • How to get whole data as it is. Don't want to truncate the input data.

    Then whatever you do, don't use a float. At least use double, but even double will struggle with that value as IEEE-754 double-precision floating point numbers are only precise to roughly 15 digits when expressed in base 10. For greater precision than that, look at BigDecimal.