问题
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 staticvalueOf(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