Search code examples
javadatabasecsvbigdecimal

Printing the values as it is using BigDecimal in Java


I need to store the exact values which is in a csv to a database. The columns has money values . So making use of BigDecimal to store money values.

Consider the following example with different cases :

Case 1:

BigDecimal d=new BigDecimal(1);
System.out.println(d);

I get '1' as output as expected.

Case 2:

But When I add a decimal to it, I get different results.

BigDecimal d=new BigDecimal(1.1);           
System.out.println(d); 

I get '1.100000000000000088817841970012523233890533447265625' as output for the above code.

Case 3:

BigDecimal d=new BigDecimal(2.50);
System.out.println(d); 

I get '2.5' as output for the above code. It is omitting the zero in this case.

My Client needs the exact same value which is passed to be stored in the database. Since , the values are money related I can't use String to store them.

So What should be done to get the exact same values which we pass into Big Decimals ?


Solution

  • You can use the constructor with String parameter.

    BigDecimal d=new BigDecimal("1");
    System.out.println(d.toString());//Will print 1
    
    
    
    BigDecimal d=new BigDecimal("1.1");           
    System.out.println(d.toString()); //Will print 1.1
    
    
    BigDecimal d=new BigDecimal("2.50");
    System.out.println(d.toString()); //Will print 2.50