Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# regarding bigdecimal.divide problem

Ranch Hand
Posts: 62
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..?

Ranch Hand
Posts: 142
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?

Marshal
Posts: 57498
175
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:

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.

 Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS