Convert string to Float not so trivial

G

Grzegorz Stasica

Hi,

Of course this
new Float("123.56").floatValue()
code will convert to float but what about string like this "123,56".
Comma is used by many countries in Europe to separate fraction.
Please don't tell me that I've to use regular expressions to replace ,
to . in order to receive float value.

Rgs.
Greg
 
J

Jon Skeet

Grzegorz Stasica said:
Of course this
new Float("123.56").floatValue()
code will convert to float but what about string like this "123,56".
Comma is used by many countries in Europe to separate fraction.
Please don't tell me that I've to use regular expressions to replace ,
to . in order to receive float value.

Use NumberFormat.parse instead, where you've created an instance of
NumberFormat which uses the appropriate Locale.
 
M

Michael Borgwardt

Grzegorz said:
Of course this
new Float("123.56").floatValue()
code will convert to float

And unnecessarily creates a throwaway object. Use Float.parseFloat() instead.
but what about string like this "123,56".
Comma is used by many countries in Europe to separate fraction.
Please don't tell me that I've to use regular expressions to replace ,
to . in order to receive float value.

java.text.DecimalFormat.parse()
 
V

VisionSet

Grzegorz Stasica said:
Hi,

Of course this
new Float("123.56").floatValue()
code will convert to float but what about string like this "123,56".
Comma is used by many countries in Europe to separate fraction.
Please don't tell me that I've to use regular expressions to replace ,
to . in order to receive float value.

DecimalFormatSymbols sym = new DecimalFormatSymbols();
sym.setDecimalSeparator(',');
DecimalFormat form = new DecimalFormat("");
form.setDecimalFormatSymbols(sym);
Number num = form.parse("123,456");
float f = num.floatValue();
System.out.println(f);

There is probably an appropriate locale option in there somewhere to.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top