Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: function to round away from zero?

Tags:

java

rounding

How do I round a double away from zero in Java?

The operations I know don't do what I want:

  • Casting it to (int) rounds it toward zero. (int) 3.7 will be 3, (int) - 3.9 will be -3.

  • Math.floor() rounds toward minus infinity. Math.floor(3.7) will be 3.0, Math.floor(-3.9) will be -4.0.

  • Math.ceil() rounds toward plus infinity. Math.ceil(3.7) will be 4.0, Math.ceil(-3.9) will be -3.0.

  • Math.round() rounds toward the nearest integer.

However I don't have something that rounds away from zero, such that 3.7 becomes 4.0, and -3.9 becomes -4.0.

Is there such a function in Java?

like image 225
Guillaume F. Avatar asked Apr 23 '20 14:04

Guillaume F.


3 Answers

Check the sign of the number:

double roundedAway = (num >= 0) ? Math.ceil(num) : Math.floor(num)
like image 187
Andy Turner Avatar answered Oct 11 '22 23:10

Andy Turner


You can either implement your own function, based on your number being positive or negative, or you can use a RoundingMode. It can round explicitly away from zero with UP

It might look something like this

DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.UP);
System.out.println(df.format(number_here));
like image 41
mnestorov Avatar answered Oct 11 '22 21:10

mnestorov


It can be done with RoundingMode and BigDecimal:

double roundAway(double value) {
    return new BigDecimal(value).setScale(0, RoundingMode.UP).doubleValue();
}

Note: this will convert the double to a BigDecimal with the precise value of the double. To avoid this, you could use BigDecimal.valueOf(double) instead of the constructor which would use the canonical string representation of the double, but since you're about to round it to a whole number, this would involve an unnecessary conversion to a string. See the constructor documentation for more details.

like image 2
David Conrad Avatar answered Oct 11 '22 23:10

David Conrad