I have this BigDecimal number - 68.65121847597993
and I want to round it like this - 68.7
, so only decimical part of number would be rounded up, but not the whole number.
I tried to use RoundingMode.HALF_UP but it rounds up the whole number as well. Is there a way to round up only decimical part of number using java?
In order to represent a number with that many decimal points, I presume you are using BigDecimal
rather than double
, which can only accurately represent approximately 15 significant digits.
Starting from a BigDecimal, which you can initialize with a string, a double, or anything else you have, you can call BigDecimal::setScale to get the value you want.
For example:
import java.math.*;
public class HelloWorld {
public static void main(String []args){
BigDecimal b = new BigDecimal("68.65121847597993");
BigDecimal rounded = b.setScale(2, RoundingMode.HALF_UP);
System.out.println(rounded); // 68.65
}
}