BigDecimal Method returns vague results, why does this happen?

ぐ巨炮叔叔 提交于 2019-12-10 10:54:19

问题


Code:

package tk.vivekpatani.www;

import java.math.BigDecimal;
import java.util.Scanner;

public class SimpleCalc {

  public static void main(String[] args) {


    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    try{
    System.out.println("Welcome to the Calculator!");


    System.out.println("Enter Number 1:");
    double num1 = sc.nextDouble();

    System.out.println("Enter Number 2:");
    double num2 = sc.nextDouble();

    BigDecimal bd1 = new BigDecimal(num1);
    BigDecimal bd2 = new BigDecimal(num2);

    BigDecimal result = addition(bd1,bd2);

    System.out.println("Result:"+result.toString());
    }
    finally{
      sc.close();
    }

  }
  static BigDecimal addition(BigDecimal input1, BigDecimal input2){

    BigDecimal result = input1.add(input2);
    return result;

  }


}

Results:

Welcome to the Calculator!
Enter Number 1:
90
Enter Number 2:
10.2
Result:100.199999999999999289457264239899814128875732421875

I'm using Eclipse IDE Mars and Java 1.8.


回答1:


Quoting the javadoc of the BigDecimal(double) constructor:

The results of this constructor can be somewhat unpredictable. [...] When a double must be used as a source for a BigDecimal, [...] use the static valueOf(double) method.

So, always use BigDecimal.valueOf(double), never new BigDecimal(double).

Scanner sc = new Scanner(System.in);

System.out.print("Enter Number 1: ");
double num1 = sc.nextDouble();

System.out.print("Enter Number 2: ");
double num2 = sc.nextDouble();

BigDecimal bd1 = BigDecimal.valueOf(num1);
BigDecimal bd2 = BigDecimal.valueOf(num2);

System.out.println("Result: " + bd1.add(bd2));

Output

Enter Number 1: 90
Enter Number 2: 10.2
Result: 100.2



回答2:


The double can't handle 0.2 properly due to the precision it uses.

Try doing this instead to create the numbers, you need to construct the BigDecimal using the Strings so that you don't carry over the double precision issue.

    System.out.println("Enter Number 1:");
    String num1 = sc.nextLine();
    BigDecimal bd1 = new BigDecimal(num1);

    System.out.println("Enter Number 2:");
    String num2 = sc.nextLine();
    BigDecimal bd2 = new BigDecimal(num2);


来源:https://stackoverflow.com/questions/32419276/bigdecimal-method-returns-vague-results-why-does-this-happen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!