Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I divide properly using BigDecimal

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?

like image 265
Jan Ajan Avatar asked May 17 '12 14:05

Jan Ajan


People also ask

How do you divide in BigDecimal?

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.

What is scale in BigDecimal divide?

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.

How accurate is BigDecimal?

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.


1 Answers

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

like image 155
Rohan Grover Avatar answered Nov 03 '22 08:11

Rohan Grover