Float to string conversion output differs

73 views Asked by At

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.

2

There are 2 answers

6
T.J. Crowder On BEST ANSWER

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.

3
Ankur Singhal On

BigDecimal never rounds automatically or loses precision it is highly preferred in calculations.

A float is a decimal numeric type represented with 32 bit.

A double is a 64 bit decimal number, so it can represent larger values than a float.

You can Use BigDecimal

public static void main(String[] args) {
        String a = "111111111111111111111.23";
        BigDecimal f = new BigDecimal(a);
        System.out.println(f);
    }

Output

111111111111111111111.23