Reputation: 337
I'm searching for the best practice to convert Float to Double without loosing precision. So far I only found that a proper way to do so is to convert the Float to String and the String to Double.
Searching the Float API I stumbled upon this method doubleValue(). I thought this is a static constructor that will return a double from my Float without loosing precision but the following code behaves like a cast:
public class Main {
public static void main(String[] args) {
Float floatNumber= 4.95f;
Double doubleNumber= floatNumber.doubleValue();
System.out.println(doubleNumber);
}
}
The output is 4.949999809265137
Searching any other documentation about this from the Float API I didn't find any documentation to tell me what exactly happens when I call that method. Does anybody have any idea? Or can someone confirm that all the method does is perform a cast my Float to a double and unbox it?
Upvotes: 1
Views: 2207
Reputation: 533500
When you use floating point, you get rounding errors which can be potentially "corrected" by rounding the result (assuming you know the precision you want). BigDecimal handles this by always knowing the precision.
float floatNumber= 4.95f;
double doubleNumber = (double) floatNumber;
System.out.println("After cast " + doubleNumber);
System.out.printf("Show two decimal places. %.2f%n", doubleNumber);
doubleNumber = Math.round(doubleNumber * 100) / 100.0;
System.out.println("After rounding to two places " + doubleNumber);
prints
After cast 4.949999809265137
Show two decimal places. 4.95
After rounding to two places 4.95
Upvotes: 0
Reputation: 1500504
The simple primitive-type cast (or even an implicit conversion) will do all you need, if you really want to preserve the value of a float:
float f = 4.95f;
double d = f;
Fundamentally 4.95f is already inaccurate - you can't represent that number exactly as a float. The exact value of floatNumber
is represented in doubleNumber
too - it's just that that value is not 4.95.
If you really care about the exact decimal digits, you should be using BigDecimal
instead (or a scaled integer).
Upvotes: 7
Reputation: 36767
Widening float to double conversion doesn't lose precision in java.
Upvotes: 2