在 Java 中四舍五入一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7925098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rounding a number up in Java
提问by Heon Jun Park
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 with
double rACT = Math.ceil(ACT);
double rSAT = Math.ceil(SAT);
double rGPA = Math.ceil(GPA);
目前我有我的程序来四舍五入到一个整数
double 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
仅供参考 - 我是一名高中生我真的不需要超级复杂的东西来做这个因为我需要我的方法少于 15 我可以浪费任何线
回答by Brendan Long
There's probably a simpler way, but the obvious is:
可能有一种更简单的方法,但显而易见的是:
double rSAT = Math.ceil(SAT * 100) / 100;
This turns a number like 2.123 into 212.3, rounds it to 213, then divides it back to 2.13.
这会将 2.123 之类的数字转换为 212.3,将其四舍五入为 213,然后再除以 2.13。
回答by Mark Peters
Usually, rounding is best done at the point of renderingthe 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.
此代码最多四舍五入到两位小数并使用上限。
double unrounded = 3.21235;
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMaximumFractionDigits(2);
fmt.setRoundingMode(RoundingMode.CEILING);
String value = fmt.format(unrounded);
System.out.println(value);
回答by Vishal
If you are looking for a string representation of a number you can do like below:
如果您正在寻找数字的字符串表示形式,您可以执行以下操作:
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(12.912385));
回答by aleph_null
The question has been asked before, check out How to round a number to n decimal places in Java
之前已经问过这个问题了,看看如何在Java中将数字四舍五入到n位小数
the simplest solution, in my opinion, is this one, by chris:
在我看来,最简单的解决方案是 chris:
double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;