Radek - 1 year ago 117

Java Question

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()`

Answer Source

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);
}
```