Dan
Dan

Reputation: 7744

Why does the value of BigDecimal not match the value supplied to it in the constructor?

I have a BigDecimal in Java. I know it is a value which would not be used in most cases. When this code is executed my command console prints out the following; 1789984896489654735783157941777104561834014693972171030528. This is not the full BigDecimal. My question is why does it not print the full number?

BigDecimal bD = new BigDecimal(1789984896489654689748964897484894895484896546845987465874.54644685486451845867467986798679864598764589459468746587946578945);
System.out.println(bD);

Upvotes: 1

Views: 202

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

The problem is the constructor that you are using: BigDecimal(double). The big long string of digits gets converted to Java's double, which does not have nearly enough precision for what you are trying to put into BigDecimal.

You need to use the BigDecimal(String) constructor instead:

BigDecimal bD = new BigDecimal("1789984896489654689748964897484894895484896546845987465874.54644685486451845867467986798679864598764589459468746587946578945");
//                             ^                                                                                                                            ^

Demo.

Upvotes: 4

Related Questions