0

i want to convert Strings (for example $2,480.00, $1.22) to float values (expecting results: 2480.00, 1.22). Which way is best to do it? By loop, leaving in string digits and '.' or maybe with regex?

mtmx
  • 827
  • 1
  • 10
  • 31
  • Assuming you know the currency signs, and the rest of the number follows the floating point spec you can just use `str.replaceAll("[$...]", "")` where the `...` is the other currency symbols. – vandench Mar 13 '18 at 13:29
  • You may have issues with number formats, (`.` vs `,`) – jrtapsell Mar 13 '18 at 13:30
  • I think [this](https://stackoverflow.com/questions/965831/how-to-parse-a-currency-amount-us-or-eu-to-float-value-in-java) is the answer you are looking for. – Alex Samson Mar 13 '18 at 13:30
  • Remove the first symbol, from the string; and then use Float.parseFloat("string") ... – Amita Mar 13 '18 at 13:35
  • Questions asking for *homework help* **must** include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it ([help], [ask]). – Zabuzard Mar 13 '18 at 14:04

3 Answers3

0

you can split your string and then use your numbers as you want :

        String str = "$2,480.00";
        str = str.replaceAll("[^-?0-9]+", " ");
        System.out.println(Arrays.asList(str.trim().split(" ")));

output :

[2, 480, 00]
Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32
0

Using NumberFormat

String s = "$2,480.00";
float num = NumberFormat.getInstance()
        .parse(s.substring(1))
        .floatValue();
System.out.println(num);

Assumptions

I have assumed the number always begins with a currency symbol

Why not remove the ,s and .s

If you do this you may have issues with international number formats, some of which change the meaning of dot and comma.

In Canadian English, a period is used as the decimal marker, and a comma (or space) is used to separate three numerals. For example, 26,000 reads as twenty-six thousand.

In French—and many other languages—a comma indicates the decimal, so 26,000 reads as twenty-six. That’s a huge difference from how an anglo would interpret it! The proper way to write twenty-six thousand in French is 26 000 or 26000. source

Community
  • 1
  • 1
jrtapsell
  • 6,719
  • 1
  • 26
  • 49
0

Just parse the string as float after removing non-number and non-dot characters:

float money = Float.parseFloat("$2,480.00".replaceAll("[^\\d.]", ""));
xingbin
  • 27,410
  • 9
  • 53
  • 103