简体   繁体   中英

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?

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

import java.math.*;
class Main{
   public static void main(String[] args) {

      // create 3 BigDecimal objects
      BigDecimal bg1, bg2, bg3;
      MathContext mc=new MathContext(10,RoundingMode.DOWN);

      bg1 = new BigDecimal("2.4",mc);
      bg2 = new BigDecimal("32301",mc);

      bg3 = bg1.divide(bg2,mc); // divide bg1 with bg2

      String str = "Division result is " +bg3;

      // print bg3 value
      System.out.println( str );
   }
}

giving wrong answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM