Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Need Parse Help for dollar amounts

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

like image 336
KevinM Avatar asked Dec 22 '22 14:12

KevinM


2 Answers

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.

like image 166
Mohamed Mansour Avatar answered Jan 06 '23 04:01

Mohamed Mansour


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.

like image 23
Greg Hewgill Avatar answered Jan 06 '23 02:01

Greg Hewgill