How can I divide properly using BigDecimal

前端 未结 1 1535
南方客
南方客 2020-11-30 04:17

My code sample:

import java.math.*; 

public class x
{
  public static void main(String[] args)
  {
    BigDecimal a = new BigDecimal(\"1\");
    BigDecimal          


        
相关标签:
1条回答
  • 2020-11-30 05:10

    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

    0 讨论(0)
提交回复
热议问题