How can I round up a figure in Java?
Hello I am new to android. I want to calculate amount in my application. If amount is 35.60 I want to display 36.00 .& if amount is 35.4 I want to display 35.00. How can i do th开发者_开发技巧is? Please help me.
You just need to use the Math.round()
method: Math.round(35.6)
returns 36 and Math.round(35.4)
returns 35 as you require.
A pretty standard way of doing that, if you don't know about any rounding function, is to add 0.5 and convert to int, like so:
int rounded = (int)(value + 0.5)
For flexibility in rounding, consider using BigDecimal like below:
BigDecimal foo = new BigDecimal(2432.77112).setScale(2, BigDecimal.ROUND_HALF_UP);
double myNativeDouble = foo.doubleValue();
There are other rounding methods available to choose from, check the javadocs for more details.
精彩评论