I tried the following,
double doubleVal = 1.745; double doubleVal1 = 0.745; BigDecimal bdTest = new BigDecimal( doubleVal); BigDecimal bdTest1 = new BigDecimal( doubleVal1 ); bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP); bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP); System.out.println("bdTest:"+bdTest); //1.75 System.out.println("bdTest1:"+bdTest1);//0.74 problemmmm ????????????
but got weird results. Why?
You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded: BigDecimal scaled = value. setScale(0, RoundingMode.
static int ROUND_HALF_UP − Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. static int ROUND_UNNECESSARY − Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
Description. The java. math. BigDecimal. setScale(int newScale, RoundingMode roundingMode) returns a BigDecimal 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.
A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.
Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.
This code works as expected (I just changed the type from double to String):
public static void main(String[] args) { String doubleVal = "1.745"; String doubleVal1 = "0.745"; BigDecimal bdTest = new BigDecimal( doubleVal); BigDecimal bdTest1 = new BigDecimal( doubleVal1 ); bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP); bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP); System.out.println("bdTest:"+bdTest); //1.75 System.out.println("bdTest1:"+bdTest1);//0.75, no problem }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With