How to round in java towards zero?
So -1.9 becomes -1.0 and -0.2 becomes 0.0, 3.4 becomes 3.0 and so on.
Is Math.round()
capable of doing this changing some parameters?
Round-toward-zero: As its name suggests, this refers to rounding in such a way that the result heads toward zero. For example, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, and 3.9 will all be rounded to 3. Similarly, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -3.7, -3.8, and -3.9 will all be rounded to -3.
It is used for rounding a decimal to the nearest integer. In mathematics, if the fractional part of the argument is greater than 0.5, it is rounded to the next highest integer. If it is less than 0.5, the argument is rounded to the next lowest integer.
HALF_UP. public static final RoundingMode HALF_UP. Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for RoundingMode. UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for RoundingMode.
Java Math round()The round() method rounds the specified value to the closest int or long value and returns it. That is, 3.87 is rounded to 4 and 3.24 is rounded to 3.
I do not believe that the standard library has such a function.
The problem is that you are asking for very different behavior (mathematically speaking) depending on whether the number is larger or smaller than 0 (i.e. rounding up for negative values, rounding down for positive values)
The following method could be used:
public double myRound(double val) {
if (val < 0) {
return Math.ceil(val);
}
return Math.floor(val);
}
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