简体   繁体   中英

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 . 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.

As others have said in the comments, NumberFormatException is happening because you are trying to parseDouble without removing the $ from the number.

In this case, you can use substring() to get everything after the first char:

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

$ 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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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