pavi
pavi

Reputation: 674

How to initialize a BigDecimal with a very precise floating point value

I have a database column with Decimal(19,5) size, I want a BigDecimal in java to store the value but if I write

 BigDecimal(999999999999999.9999);

the value is rounded to 1+E15 which I don't want it to be,So how can I get the complete precision of the number.

One way I know is using

BigDecimal("999999999999999.9999");

I thought there should be a better option to specify the precision.

Upvotes: 4

Views: 8958

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

You need to use a constructor that takes a String because the value of double constant is rounded by the compiler well before it gets to the BigDecimal's constructor. In other words, the compiler sees your 999999999999999.9999 constant, and converts it to double. The double type does not have enough precision to store all the nines, so the value gets rounded to 1+E15, and that's the value that gets passed to BigDecimal's constructor. The precision is gone before the program gets to execute its first instruction.

On the other hand, when you pass a string, you let BigDecimal do the interpretation of the sequence of nines, making sure that you get the exact precision that you need.

Upvotes: 9

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

The main reason that you have to use BigDecimal here is that the value will not fit into the double type. The double value will get rounded when passed into the constructor of BigDecimal, so no matter what you do you can not recover the original value, if you pass just a double. So you have no better option - use BigDecimal like you do.

Upvotes: 2

Related Questions