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? trueSo 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.
Really?
Float: 0.1
Double: 0.10000000149011612
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