programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Tim Cooke
• Paul Clapham
• Jeanne Boyarsky
Sheriffs:
• Ron McLeod
• Frank Carver
• Junilu Lacar
Saloon Keepers:
• Stephan van Hulst
• Tim Moores
• Tim Holloway
• Al Hobbs
• Carey Brown
Bartenders:
• Piet Souris
• Frits Walraven
• fred rosenberger

# Arithmatic calculations using Big Decimals

Greenhorn
Posts: 1
• • Number of slices to send:
Optional 'thank-you' note:
• • Hi

I have a calculation using big decimal values x, y=7888 and z= 4902 as below:
x = (y * 1000 / z)
I get arithmatic error as "Non-terminating decimal expansion" without rounding up. But the required result is 1609.13913, where as with calculation below I am getting result as 1609.15200.
System.out.println(new BigDecimal("7888").multiply(new BigDecimal("1000").divide(new BigDecimal("4902"),5,BigDecimal.ROUND_HALF_UP)));
Even as I use:
System.out.println(new BigDecimal("7888").multiply(new BigDecimal("1000").divide(new BigDecimal("4902"),11,BigDecimal.ROUND_HALF_UP)));
The result is coming as 1609.13912686288.

Bartender Posts: 10780
71   • • Number of slices to send:
Optional 'thank-you' note:
• • Huma Rangwani wrote:I get arithmatic error as "Non-terminating decimal expansion" without rounding up.

Which simply means that the result cannot be represented by a decimal number (which is quite often the case).

But the required result is 1609.13913, where as with calculation below I am getting result as 1609.15200.
System.out.println(new BigDecimal("7888").multiply(new BigDecimal("1000").divide(new BigDecimal("4902"),5,BigDecimal.ROUND_HALF_UP)));

And that's because your bracketing is wrong. In cases like this it's usually a good idea to write "dumb" code, and spread things out a bit, rather than piling everything together in one statement, viz:and now look at your statement:NOW do you see where the problem is?

Winston Always look on the bright side of life. At least this ad is really tiny: the value of filler advertising in 2021 https://coderanch.com/t/730886/filler-advertising