Reputation: 1949
Suppose I'm supplied with a String which is like "$123,456,56.25"
or "123'456.67"
or something similar to this (with digits and a decimal point and some seperator like ,
or '
or something else which is not predictable). I need to write a method which takes an argument like the one above and returns a String like "12345656.25"
or "123456.67"
respectively.
Could you please suggest the most efficient and readable code to achieve this?
Note: I'm aware of going through each indexes and checking for whether its retunrs true
for Character.isDigit(charAtInedx)
or if(charAtInedx == '.')
I'm looking for a more optimized solution both in terms of efficiency and readability
Thanks.
Upvotes: 10
Views: 26469
Reputation: 1
To parse a currency instance in Java, you can use the NumberFormat.getCurrencyInstance
object. For example:
import java.text.NumberFormat;
import java.text.ParseException;
public class Main {
public static void main(String[] args) throws ParseException {
NumberFormat currency = NumberFormat.getCurrencyInstance(); // get the currency formatter
String price = currency.format(19292.282); // format as a currency
System.out.println(price); // $19,292.28
Number parsePrice = currency.parse(price);
System.out.println(parsePrice); // 19292.28
}
}
Keep in mind that this is just a quick example, and you would need to account for exceptions as well.
Upvotes: 0
Reputation: 3549
If you want to handle monetary values correctly, you will want to have a look at the NumberFormat class, specifically for your case NumberFormat.parse(String). The following article also discusses the problems (and solutions) to handling money in Java:
http://www.javapractices.com/topic/TopicAction.do?Id=13
Other related classes include: Currency and of course BigDecimal.
Upvotes: 8
Reputation: 298908
String newStr = oldStr.replaceAll("[^\\d.]+", "")
This will drop any character that is not either a digit or a period
Upvotes: 19