Floating to 2 decimal places
•
Java
I want to add two decimals to a floating point number
I have 2 floating point values:
1.985 29.294998
They all need to be rounded, so I'm done with the following:
1.99 29.30
When I use the following methods:
public static Float precision(int decimalPlace,Float d) { BigDecimal bd = new BigDecimal(Float.toString(d)); bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP); return bd.floatValue(); }
The result is:
1.99 29.29
Solution
Because you use BigDecimal ROUND_ HALF_ Up, so 29.294998 is rounded to 29.29 You may want to use BigDecimal ROUND_ UP.
Check BigDecimal doc for more information about each rounding
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码