My code sample:
import java.math.*; public class x { public static void main(String[] args) { BigDecimal a = new BigDecimal("1"); BigDecimal b = new BigDecimal("3"); BigDecimal c = a.divide(b, BigDecimal.ROUND_HALF_UP); System.out.println(a+"/"+b+" = "+c); } }
The result is: 1/3 = 0
What am I doing wrong?
divide(BigDecimal divisor) is used to calculate the Quotient of two BigDecimals. The Quotient is given by (this / divisor). This method performs an operation upon the current BigDecimal by which this method is called and the BigDecimal passed as the parameter.
These scales are the ones used by the methods which return exact arithmetic results; except that an exact divide may have to use a larger scale since the exact result may have more digits. For example, 1/32 is 0.03125.
This limits it to 15 to 17 decimal digits of accuracy. BigDecimal can grow to any size you need it to. Double operates in binary which means it can only precisely represent numbers which can be expressed as a finite number in binary. For example, 0.375 in binary is exactly 0.011.
You haven't specified a scale for the result. Please try this
2019 Edit: Updated answer for JDK 13. Cause hopefully you've migrated off of JDK 1.5 by now.
import java.math.BigDecimal; import java.math.RoundingMode; public class Main { public static void main(String[] args) { BigDecimal a = new BigDecimal("1"); BigDecimal b = new BigDecimal("3"); BigDecimal c = a.divide(b, 2, RoundingMode.HALF_UP); System.out.println(a + "/" + b + " = " + c); } }
Please read JDK 13 documentation.
Old answer for JDK 1.5 :
import java.math.*; public class x { public static void main(String[] args) { BigDecimal a = new BigDecimal("1"); BigDecimal b = new BigDecimal("3"); BigDecimal c = a.divide(b,2, BigDecimal.ROUND_HALF_UP); System.out.println(a+"/"+b+" = "+c); } }
this will give the result as 0.33. Please read the API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With