Java四舍五入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3705722/
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
Java Rounding Up
提问by LordRazon
How can I rould the value of the numberGrade up so if it is 89.5 it goes to 90. numberGrade is taken in as a double but making it a int does not round it up or down.
我怎样才能将 numberGrade 的值向上调整,如果它是 89.5,它会变为 90。 numberGrade 被视为双精度值,但使其成为 int 不会向上或向下舍入。
public class GradeReporter
{
// The limit is the inclusive lower limit for each letter
// grade -- this means that 89.5 is an 'A' not a 'B'
public static final double A_LIMIT = 90;
public static final double B_LIMIT = 80;
public static final double C_LIMIT = 70;
public static final double D_LIMIT = 60;
public static final double F_LIMIT = 60;
/** Converts a numeric grade into a letter grade. Grades should be rounded to
* nearest whole number
*
* @param a numeric grade in the range of 0 to 100
* @returns a letter grade based on the numeric grade, possible grades are A, B, C, D and F.
*/
public char letterGrade(double numberGrade)
{
int grade = int(numberGrade);
if (grade >= A_LIMIT)
letterGrade = 'A';
else if (grade >= B_LIMIT)
letterGrade = 'B';
else if (grade >= C_LIMIT)
letterGrade = 'C';
else if (grade >= D_LIMIT)
letterGrade = 'D';
else if (grade < F_LIMIT)//4
letterGrade = 'F';
return letterGrade;
}
回答by Jeff
To round up, you can use Math.ceil(numberGrade)
. To round to the nearest integer, use Math.round(numberGrade)
.
为了圆了,你可以使用Math.ceil(numberGrade)
。要四舍五入到最接近的整数,请使用Math.round(numberGrade)
。
See: the Math
class
请参阅:在Math
类
回答by clstrfsck
You could use either:
您可以使用:
int intGrade = (int)(doubleGrade + 0.5);
Or
或者
long longGrade = Math.round(doubleGrade);
int intGrade = (int)longGrade;
回答by I82Much
Are you saying you want all decimal parts rounded up - 89.2 rounds to 90? If that's the case, use Math.ceil(double val).
您是说要将所有小数部分四舍五入 - 89.2 舍入为 90?如果是这种情况,请使用 Math.ceil(double val)。
If instead you want to round to the nearest number (89.2 rounds to 89, 89.6 rounds to 90), you'd want to do java.lang.StrictMath.round(float val)
相反,如果您想四舍五入到最接近的数字(89.2 舍入到 89,89.6 舍入到 90),您需要执行java.lang.StrictMath.round(float val)