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?
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);
}
cast to long like this:
float x= 1.9;
long y = (long)x;
This rounds both positive and negative numbers towards zero.
Use RoundingMode.DOWN
, it leads towards zero.
Example :
BigDecimal value = new BigDecimal("1.4");
value = value.setScale(0, RoundingMode.DOWN);
System.out.println(value.doubleValue());
BigDecimal value1 = new BigDecimal("-1.4");
value1 = value1.setScale(0, RoundingMode.DOWN);
System.out.println(value1.doubleValue());
Just casting to int will do that for you?
Edit: If you want to retain a double this should work simply enough:
if (val < 0)
return -Math.floor(-val);
else
return Math.floor(val);
And just for the people who want branch free code and feel a bit more clever:
long tmp = Double.doubleToLongBits(val);
tmp >>>= 63;
return Math.floor(val) + tmp;
y=sign(x)*floor(abs(x))
or
y=sign(x)*round(abs(x)-0.5)
It should be easy to implement in Java.
Seems like you want to always round-down? You can use Math.floor
instead
public static double floor(double a)
Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer. Special cases:
BigDecimal
offers many rounding options.
You also can try this:
public static void main(String[] args) {
Double myDouble = -3.2;
System.out.println(myDouble.intValue()); //Prints -3
}