四舍五入到最近的一百个 [英] Rounding Up To The Nearest Hundred
问题描述
我参与了我的java程序,在那里我需要四舍五入到最接近的百位并且认为可能有某种方法可以做到,但我猜不是。所以我搜索了网上的例子或任何答案,我还没有找到任何答案,因为所有的例子似乎都是近一百个。我只是想做这个并且向上舍入。也许有一些我忽略的简单解决方案。我已经尝试了 Math.ceil
和其他功能但尚未找到答案。如果有人可以帮我解决这个问题,我将非常感激。
I came to a part in my java program where I need to round up to the nearest hundred and thought that there was probably some way to do it but I guess not. So I searched the net for examples or any answers and I've yet to find any since all examples appear to be to the nearest hundred. I just want to do this and round UP. Maybe there's some simple solution that I'm overlooking. I have tried Math.ceil
and other functions but have not found an answer as of yet. If anyone could help me with this issue I would greatly appreciate it.
如果我的数字是203,我希望结果四舍五入为300.你明白了。
If my number is 203, I want the result rounded to be 300. You get the point.
- 801-> 900
- 99-> 100
- 14-> 100
- 452-> 500
- 801->900
- 99->100
- 14->100
- 452->500
推荐答案
利用整数除法,它会截断商的小数部分。为了让它看起来像四舍五入,先添加99.
Take advantage of integer division, which truncates the decimal portion of the quotient. To make it look like it's rounding up, add 99 first.
int rounded = ((num + 99) / 100 ) * 100;
示例:
801: ((801 + 99) / 100) * 100 → 900 / 100 * 100 → 9 * 100 = 900
99 : ((99 + 99) / 100) * 100 → 198 / 100 * 100 → 1 * 100 = 100
14 : ((14 + 99) / 100) * 100 → 113 / 100 * 100 → 1 * 100 = 100
452: ((452 + 99) / 100) * 100 → 551 / 100 * 100 → 5 * 100 = 500
203: ((203 + 99) / 100) * 100 → 302 / 100 * 100 → 3 * 100 = 300
200: ((200 + 99) / 100) * 100 → 299 / 100 * 100 → 2 * 100 = 200
相关的 Java语言规范引用,第15.17节.2 :
整数除法向0舍入。也就是说,为
操作数n和d生成的商二进制数字促销后的整数
(§5.6.2)是一个整数值q,其大小尽可能大
,同时满足| d·q | ≤| n |。
Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|.
这篇关于四舍五入到最近的一百个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!