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?
Check the sign of the number:
double roundedAway = (num >= 0) ? Math.ceil(num) : Math.floor(num)
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With