aseolin
aseolin

Reputation: 1200

Convert String to Float preserving decimal places

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.

Upvotes: 0

Views: 1292

Answers (1)

Matthieu
Matthieu

Reputation: 3098

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.

Upvotes: 3

Related Questions