The follow code round incorrectly for a human people:
double d = 0.7F;
System.out.println( d );
print the value: 0.699999988079071
The follow code work better:
double d = Double.valueOf( Float.toString( 0.7F ));
System.out.println( d );
But create an additional String. Are there a more performance conversion of float to double without an extra string?
The code line are simple and demonstrate only the problem. The program is more complex. The float values are in a one part of a complex model. The formatting layer use only double. Also DecimalFormat accept only double and not float.
If you know what precision you want you can round it to say 6 decimal places. eg.
public static double round6(double x) {
return Math.round(x * 1e6) / 1e6;
}
round6(0.7f) == 0.7
The fact the x
passed in was a float
doesn't matter provided this precision is suitable.