Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round towards zero in java

Tags:

java

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?

like image 601
Radek Avatar asked Dec 05 '11 15:12

Radek


People also ask

How do you round to zero?

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.

Does Java round 0.5 up or down?

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.

What is RoundingMode Half_up in Java?

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.

How do you round off in Java?

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.


1 Answers

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);
}
like image 138
Kris Avatar answered Oct 12 '22 13:10

Kris