I'm trying to figure out a way to parse the "$" and "," out of a dollar amount.
For example, say I have a String that is $5,600. I need to parse it so what I have left is just 5600. Any开发者_如何学编程 help is great appreciated.
Thank you, Kevin
You use the NumberFormat
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse("$5,600");
number
will be 5600
You can specify a locale if you want to target special countries.
In principle, you can do the following two steps:
- Remove the leading
$
(if any). - Remove any embedded commas.
Optionally, you can then check to make sure that what you're left with is all digits.
You can do this using the startsWith
, substring
, and replace
methods of String
, but there are many ways you could go about it.
How about using DecimalFormat
? Remember, the Format
classes can be used for string parsing as well as string formatting.
精彩评论