Question

I am programming for the first time with BigDecimals.

Why is the behaviour different in follwing two programs

   1) BigDecimal d = new BigDecimal("2.01").setScale(4);
      System.out.println(d);
      Gives me : 2.0100

  And 

   2) BigDecimal d = new BigDecimal("2.01");
      d.setScale(4);
  System.out.println(d);  
      Gives me : 2.01

Why is this so?

Also I am having a functionality where I need to compare a row in CSV file with DB record record using some BigDecimal value. DB columns have DB type as Decimal with different scales e.g Quantity is the column with scale defined as 4. when user enters value of quantity as 2 in CSV file it is retrieved as follows:

     BigDecimal q = new BigDecimal("2");
     which gives me big decimal with scale as 0 and precision as 1 with value as 2.

when I retrieve the same value from DB using

      rs.getBigDecimal(54) where 54 is column index, 
  I get Big decimal with precision as 0 and scale as 4 with value as 2.0000

Now As I have to compare hundreds of records in CSV in all the records in DB, I was thinking of creating SHA1 value of all the records in DB and compare it with SHA1 value of contents of CSV record.
However I don't understand how to have same string representation of two bigdecimals with same value with different precision. I know 2 and 2.0000 are not technically same for computer but for users they are same.
So I want to have same representation of them. I also tried calculating their hashcodes but they are also different which is right as they are altogether different numbers for computer.
So how can I have 2 as BigDecimal being converted to 2.0000 Bigdecimal so that I can get same String representation.

this is really proving to be a blocker for me

Was it helpful?

Solution

If I understand you, you've missed the assignment from the result of setScale();

d = d.setScale(4);

Edit

As for your second question, you can call stripTrailingZeros() -

d = d.stripTrailingZeros();

OTHER TIPS

BigDecimal is immutable. By calling:

d.setScale(4);

You just create new instance and dont't use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top