在 Java 中对数字进行四舍五入
我不明白如何将数字四舍五入到某些小数位 我到处找,尝试了
目前我的程序,将其四舍五入为整数 双 rACT = Math.ceil(ACT); 双 rSAT = Math.ceil(SAT); double rGPA = Math.ceil(GPA);
但我需要它四舍五入到小数点后两位
仅供参考 - 我是一名高中生,我真的不需要超级复杂的东西 为了做到这一点,因为我需要我的方法少于 15 个,我可以浪费任何行
I dont get how rounding numbers up to certain decimal places
I looked everywhere tried every thing
currently I have my program to round up to a whole number withdouble rACT = Math.ceil(ACT);
double rSAT = Math.ceil(SAT);
double rGPA = Math.ceil(GPA);
but i need it to round up to 2 decimal places
FYI - I am an High school student I really dont need something super complicated
to do this cuz I need my methods to be less then 15 I can waste any lines
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能有一种更简单的方法,但显而易见的是:
这会将 2.123 这样的数字转换为 212.3,将其四舍五入为 213,然后将其除回 2.13。
There's probably a simpler way, but the obvious is:
This turns a number like 2.123 into 212.3, rounds it to 213, then divides it back to 2.13.
通常,四舍五入最好在渲染数字时完成(例如作为字符串)。这样,可以以最高精度存储/传递数字,并且信息仅在向用户显示时才会被截断。
此代码最多四舍五入到小数点后两位并使用上限。
Usually, rounding is best done at the point of rendering the number (as a String, e.g.). That way the number can be stored/passed around with the highest precision and the information will only be truncated when displaying it to a user.
This code rounds to two decimal places at most and uses ceiling.
这个问题之前已经被问过,请查看如何在 Java 中将数字四舍五入到 n 位小数
在我看来,最简单的解决方案是 chris 的这个:
The question has been asked before, check out How to round a number to n decimal places in Java
the simplest solution, in my opinion, is this one, by chris:
如果您正在寻找数字的字符串表示形式,您可以执行以下操作:
If you are looking for a string representation of a number you can do like below: