如何将 Java 中的 String 值转换为 Double 或 Int 值?

How to Convert String value into Double or Int value in Java?

我有问题。我的 String 的值为 "5.00",我想将其转换为 doubleint。 我试过下面的代码但是有一个错误:

String one = "5.00";
String two = ".00";
double newone = Double.parseDouble( one );
double newtwo = Double.parseDouble( two );

System.out.println(newone-newtwo);

错误是

Exception in thread "main" java.lang.NumberFormatException: For input string: "5.00"

但是我已经为方法添加了NumberFormatException,但仍然出现错误。

使用正则表达式删除“$”等符号(换句话说,除数字和点之外的所有符号)

String one = "5.03";
String oneValue = one.replaceAll("[^0-9.]", "");
System.out.println(oneValue); // Output is 615.03, which is correctly parsed by parseDobule()

正如其他人在评论中所说,发生 NumberFormatException 是因为您试图在不从数字中删除 $ 的情况下解析 parseDouble。

在这种情况下,您可以使用 substring() 获取第一个字符后的所有内容:

String one = "5.00";
String two = ".00";

double newone = Double.parseDouble( one.substring(1) );
double newtwo = Double.parseDouble( two.substring(1) );

System.out.println(newone-newtwo);

结果为 600.00

$ 是货币指示符。它不是数值的一部分。

如果您有货币价值,您应该使用 currency format 来读取它:

NumberFormat format = NumberFormat.getCurrencyInstance();
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();

如果您 运行 的计算机不是为美国配置的,您可能需要传递区域设置,以强制货币实例使用美元:

NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();