简体   繁体   English

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

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

I have a problem.我有个问题。 I have String with the value "$615.00" and I want to convert it to double or int .我有值为"$615.00" String ,我想将其转换为doubleint I have tried the following code but there is an error:我尝试了以下代码,但出现错误:

String one = "$615.00";
String two = "$15.00";
double newone = Double.parseDouble( one );
double newtwo = Double.parseDouble( two );

System.out.println(newone-newtwo);

The error is错误是

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

But I have added the NumberFormatException for the method and still got the error.但是我为该方法添加了NumberFormatException并且仍然出现错误。

As others have said in the comments, NumberFormatException is happening because you are trying to parseDouble without removing the $ from the number.正如其他人在评论中所说的那样,发生 NumberFormatException 是因为您试图 parseDouble 而不从数字中删除 $ 。

In this case, you can use substring() to get everything after the first char:在这种情况下,您可以使用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);

Results in 600.00结果在 600.00

$ is a currency designator. $是货币指示符。 It is not part of a numeric value.它不是数值的一部分。

If you have a currency value, you should use a currency format to read it:如果您有货币值,则应使用货币格式来读取它:

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

If you are not running on a computer configured for the US, you may need to pass a Locale, to force the currency instance to use US dollars:如果您没有在为美国配置的计算机上运行,​​则可能需要传递 Locale,以强制货币实例使用美元:

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

Use regular expression to remove symbols like "$" (in other words, all symbols but digits and dot)使用正则表达式删除像“$”这样的符号(换句话说,除了数字和点之外的所有符号)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM