开发者

Java - Need Parse Help for dollar amounts

开发者 https://www.devze.com 2023-03-02 07:40 出处:网络
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开发者_如何

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:

  1. Remove the leading $ (if any).
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消