Vijay
Vijay

Reputation: 663

String to float/double Parsing

When I try to parse the following string into a float and into a double :

String abc = "8.40";
System.out.println("Double Value: " + Double.parseDouble(abc) * 100);
System.out.println("Float Value: " + Float.parseFloat(abc) * 100);

I get two different results.

Double Value: 840.0
Float Value: 839.99994

But when I try the same code with multiplying the float and double by 10 or 1000 I get the similar results for both of them.

String abc = "8.40";
System.out.println("Double Value: " + Double.parseDouble(abc) * 10);
System.out.println("Float Value: " + Float.parseFloat(abc) * 10);

I get two similar results.

Double Value: 84.0
Float Value: 84.0

And when I try this :

String abc = "8.40";
System.out.println("Double Value: " + Double.parseDouble(abc) * 1000);
System.out.println("Float Value: " + Float.parseFloat(abc) * 1000);

I get two similar results.

Double Value: 8400.0
Float Value: 8400.0

Upvotes: 3

Views: 1225

Answers (2)

AhmadWabbi
AhmadWabbi

Reputation: 2197

It is true that double has more precision than float, but both of them suffer from the same problem: their value may not be exact, and they both have some (small) rounding error in their Least Significant Bit (LSB). This is clear in the first result you got: float value is not accurate. But when you multiply by 10 or 1000, the LSB is discarded from the result, and so you get the right answer for both float and double.

Upvotes: 2

Adnan Isajbegovic
Adnan Isajbegovic

Reputation: 2307

This will work fine:

System.out.println("Float Value: "+Math.round((float)Float.parseFloat(abc)*100));

So, this happens because of different representation of double and float, or more precise, about IEEE-754 rounding for float. Read about it here.

float has a smaller range and precision, so double would be better when you have memory (which you do today). But, they are both evil! There is a better option in Java called BigDecimal and you should use it, since it doesn't have problem with size and today we have strong computers so we will not have problems with memory and speed when dealing with a large number of decimal numbers needing max precision. For example, if you work on software that deals with a lot of money transactions, its a must to use BigDecimal.

Upvotes: 4

Related Questions