Home java Math rounding in java

Math rounding in java




The function in java Math.ceil () should round the number up when dividing, i.e. to the right
So when dividing 12/5 = 2.4, then Math.ceil (12/5) = 3;

public static void main (String [] args) {
    System.out.println (Math.ceil (12/5));

Outputs me 2.0, Math.floor (12/5) also outputs 2.0. Maybe I don’t understand correctly how they work?

Answer 1, authority 100%

For convenience of any rounding, it is best to use the BigDecimal class:

new BigDecimal (12.0 / 5) .setScale (0, RoundingMode.CEILING) .doubleValue ();

The first parameter indicates to what sign the rounding is, and the second indicates the rounding rule.

Answer 2, authority 90%

The fact is that 12/5 is itself an integer division, the result is already 2 .

Math.ceil (12.0 / 5) == 3.0

Answer 3

The problem is that in java there are no special operators like div or mod like in Pascal. Therefore, the / sign works like an integer division of 12/5 and is really 2 (and a remainder of 2). That is why, if we want to get a fraction, we need to customize the integer divisor and the dividend to float. And you can do it as you like. At least 12f / 5f , at least (float) a / (float) b . And only after that you can round-up, etc.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions