Reputation: 53
I want to convert a string (for example $4.50) to a double. I understand I can use Double.parseDouble() but I assume this works only if the string does not contain any other chars (such as the dollar sign). The purpose is to compare two Strings (which contain dollar values plus a dollar sign) and determine which one is greater and which one is smaller
How can I convert such a string to a double?
Upvotes: 2
Views: 2412
Reputation: 1157
Hope this would help,
Double.parseDouble(string.replaceAll("[^\\d.]", ""));
Upvotes: 0
Reputation: 13650
You can do the following:
Double.parseDouble(string.replaceAll("[$]", ""));
Upvotes: 0
Reputation: 174874
Use Double.parseDouble
after removing the unwanted characters like currency symbols.
Double.parseDouble(string.replaceAll("[^\\d.]", ""));
This would removed any character but not of a dot or a digit.
Upvotes: 2