[英]How to Convert String value into Double or Int value in Java?
我有个问题。 我有值为"$615.00"
String
,我想将其转换为double
或int
。 我尝试了以下代码,但出现错误:
String one = "$615.00";
String two = "$15.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: "$615.00"
但是我为该方法添加了NumberFormatException
并且仍然出现错误。
正如其他人在评论中所说的那样,发生 NumberFormatException 是因为您试图 parseDouble 而不从数字中删除 $ 。
在这种情况下,您可以使用substring()获取第一个字符之后的所有内容:
String one = "$615.00";
String two = "$15.00";
double newone = Double.parseDouble( one.substring(1) );
double newtwo = Double.parseDouble( two.substring(1) );
System.out.println(newone-newtwo);
结果在 600.00
$
是货币指示符。 它不是数值的一部分。
如果您有货币值,则应使用货币格式来读取它:
NumberFormat format = NumberFormat.getCurrencyInstance();
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();
如果您没有在为美国配置的计算机上运行,则可能需要传递 Locale,以强制货币实例使用美元:
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();
使用正则表达式删除像“$”这样的符号(换句话说,除了数字和点之外的所有符号)
String one = "$615.03";
String oneValue = one.replaceAll("[^0-9.]", "");
System.out.println(oneValue); // Output is 615.03, which is correctly parsed by parseDobule()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.