# regarding bigdecimal.divide problem

suresh sai

Ranch Hand

Posts: 62

posted 7 years ago

Hi all.,

I have a small ( or big) problem with BigDecimal. While dividing ,especilly with double values ,it`s giving the values that is rounded. Let us suppose, I have the following code.

BigDecimal amount = new BigDecimal(0.1);

BigDecimal size = new BigDecimal(1);

If I divide amount by size its giving 0.12 rather 0.1. Please help me How can I get rid of this..?

Thanks in Advace

I have a small ( or big) problem with BigDecimal. While dividing ,especilly with double values ,it`s giving the values that is rounded. Let us suppose, I have the following code.

BigDecimal amount = new BigDecimal(0.1);

BigDecimal size = new BigDecimal(1);

If I divide amount by size its giving 0.12 rather 0.1. Please help me How can I get rid of this..?

Thanks in Advace

Tom Johnson

Ranch Hand

Posts: 142

posted 7 years ago

Firstly I suggest using the string constructor on big decimal. Anyway, how do you perform the divide? I tried the following:

My results were

0.1

0.10

0.1

If I change the code to use the double constructor of BigDecimal, I get the following results:

0.1000000000000000055511151231257827021181583404541015625

0.10

0.1

So I dont see how you got 0.12, can you post the full code?

My results were

0.1

0.10

0.1

If I change the code to use the double constructor of BigDecimal, I get the following results:

0.1000000000000000055511151231257827021181583404541015625

0.10

0.1

So I dont see how you got 0.12, can you post the full code?

<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>

Campbell Ritchie

Sheriff

Posts: 49472

64

posted 7 years ago

Please post more details: I can't see how you can get 0.12 out of even the most imprecise double division of 0.1 / 1.

I tried what you describe and got 0.1000000000000000055511151231257827021181583404541015625, which is the result of imprecision in the double arithmetic. Note the difference between the two lines in this code snippet:It produces this result:

That might sort out your problem.

By the way: there is a static field ONE in the BigDecimal class which you might find useful.

I tried what you describe and got 0.1000000000000000055511151231257827021181583404541015625, which is the result of imprecision in the double arithmetic. Note the difference between the two lines in this code snippet:It produces this result:

The result of dividing 0.1 by 1 in BigDecimal is 0.1000000000000000055511151231257827021181583404541015625

and if you use Strings you get 0.1

That might sort out your problem.

By the way: there is a static field ONE in the BigDecimal class which you might find useful.