In my application, I am using float value to hold customer score. And as per the requirement, the score may have only 5 decimal digits before the points and three digits after the points.
For example : 99999.999
But, I did not understand the strange behavior while printing float values using sysout.
Refer sample code below for more details :
public class Test {
public static void main(String[] args) {
float f1 = 9999.999f;
System.out.println(f1);
float f2 = 99999.999f;
System.out.println(f2);
}
}
And the Output is :
9999.999
100000.0
Here, why the value "99999.999" got auto incremented to "100000.0" while doing using sysout ? And why the same thing was not happened while using value of four decimal digits before the point i.e "9999.999" ?
Any suggestion appreciated.
From java specifications:
float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
To conclude if you want to save memory and you don't care about precission use float otherwise use double. More info here https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
I suggest to use BigDecimal and use the setScale method for your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With