Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

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?

like image 331
aliplane Avatar asked Sep 17 '12 13:09

aliplane


People also ask

How do you round BigDecimal numbers?

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.

What is Round_half_up in Java?

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.

What is rounding mode in BigDecimal Java?

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.

What does BigDecimal scale mean?

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.


1 Answers

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 } 
like image 181
Augusto Avatar answered Sep 23 '22 15:09

Augusto