Pages

Saturday, March 30, 2013

Float to double conversion in Java

The first thing what we learn about representation of real number in computer systems is that it is only an approximation. Some of the real numbers cannot be expressed as floating point number (see this converter). How accurate our approximation is depends how many bytes we use to represent it. That is why you may be surprised about the result of the flowing code:
float fvar=0.1f;
double dvar=(double)fvar;
System.out.print("Are these number equal? ");
System.out.println(dvar==fvar);
System.out.println("Really?");
System.out.println("Float: "+fvar);
System.out.println("Double: "+dvar);
Are these number equal? true
Really?
Float: 0.1
Double: 0.10000000149011612
So if you need to convert some floats number to double and you would like to be sure that you won't scare your customer by charging her $99.99999998989 (quite easy to miss the dot) you need to convert floats to doubles by other means.

There are a three popular ways of doing this:
float fvar=0.1f;

//1. Convert float variable to string and then parse it as a double 
Double.parseDouble(new Float(fvar).toString());

//2. Use FloatingDecimal class
new sun.misc.FloatingDecimal(fvar).doubleValue();

//3. Use BigDecimal class 
new BigDecimal(String.valueOf(fvar)).doubleValue();
All of them do the work. The question is which one is the fastest? I've used the Brent Boyer's microbenchmark to answer this question. Here is the result. As you can see the method uses the FloatingDecimal class is the quickest one.


0 komentarze:

Post a Comment