开发者

How can I round up a figure in Java?

开发者 https://www.devze.com 2023-04-06 13:43 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号