Java Rounding Up

How can I increase the value of numberGrade, so if it is 89.5, it is 90. numberGrade is taken as double, but makes it int does not round it up or down.

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;
    }
+3
source share
3 answers

To round you can use Math.ceil(numberGrade). To round to the nearest integer, use Math.round(numberGrade).

See: classMath

+18
source

You can use either:

    int intGrade = (int)(doubleGrade + 0.5);

or

    long longGrade = Math.round(doubleGrade);
    int  intGrade  = (int)longGrade;
+2
source

, - 89,2 90? Math.ceil(double val).

(89,2 89, 89,6 90), java.lang.StrictMath.round(float val)

0
source

Source: https://habr.com/ru/post/1764623/


All Articles