Reputation: 11
I want to convert 1256.3648 to 126.36 (up to 2 decimal places)
To implement this thing, I am using .setScale(2, BigDecimal.ROUND_HALF_UP));
But for some reasons, it doesn't work
Any idea?
Upvotes: 1
Views: 747
Reputation: 26185
Here is a test program demonstrating the rounding:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
BigDecimal x = new BigDecimal("1256.3648");
BigDecimal y = x.setScale(2,BigDecimal.ROUND_HALF_UP);
System.out.println(x);
System.out.println(y);
}
}
It outputs:
1256.3648
1256.36
x
is unchanged, but the result of the setScale
call is properly rounded.
Upvotes: 2
Reputation: 8207
You can do it this way
.setScale(2, RoundingMode.FLOOR);
Assuming you are calling it on the BigDecimal
object
will o/p
1256.36
If your input is 1256.3648
Remember,
java.math.BigDecimal.setScale(int newScale, RoundingMode roundingMode)
returns aBigDecimal
whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
Upvotes: 2