将 String 转换为 Double 进行计算会导致小数出现问题,如何四舍五入?

Converting String to Double for calculation cause me problem with decimal numbers, how to round it?

我发现很多关于将 String 转换为 Double(带两位小数)的答案,但我遇到了一个奇怪的情况。打印值的时候没问题,是对的。但是当我进行计算时,程序表现得很奇怪。

我有这个代码:

String str = "21.90";

我想将此字符串转换为双精度数。我尝试了很多解决方案,但 none 工作正常。

double amount = Double.valueOf(str);

double amount = Double.parseDouble(str);

try {
    amount = DecimalFormat.getNumberInstance().parse(str).doubleValue();
}
catch (ParseException e){
    // error
}

我也尝试过舍入方法,例如:

double roundOff = Math.round(amount * 100.0) / 100.0;

数字转换为“21.9”但是当我这样做时,例如:

System.out.println(number - 21.8) = 0.09999999999999787

我不明白为什么要这样做。

在此先感谢您的帮助。

当你用double进行计算时你会失去精度,为了进行计算,最好使用BigDecimal,所以我会去:

String str = "21.90";
BigDecimal result = new BigDecimal(str).subtract(BigDecimal.valueOf(21.8));
System.out.println(result);
=> 0.10

System.out.println 正在使用字符串,double 被转换为字符串 .双精度值根本没有精度,即使您的字符串有 2 位小数。

因此需要对转换后的字符串进行格式化:

String str = "21.90";
double amount = Double.parseDouble(str);
System.out.println("double is: " + amount);

double roundOff = Math.round(amount * 100.0) / 100.0;
System.out.println("double rounded is: " + roundOff);

The output is:
double is: 21.9
double rounded is: 21.9
result is: 0,10
Because of my Locale DE a comma is used in the output. Or use:

System.out.println("result is: " + String.format(Locale.US,"%.2f",amount - 21.8));

System.out.println("result is: " + String.format("%.2f",amount - 21.8));