0

I have some Java Strings formatted as Brazilian money with 4 decimal places, like:

1.000.000,0000 (1 million)
3,9590 (3 dollar and 9590 cents)
253,8999
10,0000

and so on...

I want to convert it into float so I can do some math with this.

How can I convert Strings to float preserving 4 decimal places? I tried Float.parseFloat() method but I always got NumberFormatException (maybe because of the comma).

Searching on web I only see people who wants to convert Float to formatted String.

aseolin
  • 1,184
  • 3
  • 17
  • 35
  • 1
    Don't use floats for money related calculation https://stackoverflow.com/a/27598164/6207294 – shb Jul 04 '19 at 17:08
  • https://stackoverflow.com/questions/5323502/how-to-set-thousands-separator-in-java – second Jul 04 '19 at 17:09
  • To prevent number format exception, you can replace the "," with "." and "." with "". This should give you a proper number in decimal format before parsing it as float. – ashish2199 Jul 04 '19 at 17:26
  • @ashish2199 please don't do that, there are nice APIs in Java to properly deal with number formatting (see [my answer](https://stackoverflow.com/a/56892426/1098603)). – Matthieu Jul 04 '19 at 17:44
  • **Bigdecimal** for *Big Decisions* – bananas Jul 04 '19 at 17:46
  • Is `1.000,0000` really one million, or one thousand? It looks like there are two different separators. – Matthieu Jul 04 '19 at 17:48
  • Sorry, I edited my question. 1.000.000,0000 represents 1 million with 4 decimal places, so 1.000.000,1000 represents 1 million and 1 cent – aseolin Jul 04 '19 at 18:05

1 Answers1

3

Use NumberFormat.parse():

NumberFormat nf = NumberFormat.getNumberInstance();
float val = nf.parse("3,9590").floatValue();

You can give a Locale to it when getting the instance, but the default will be your current locale.

Matthieu
  • 2,736
  • 4
  • 57
  • 87