I'm having some dificulties in converting from string to float. I get
a number format exception... This is suposed to be easy but i can't
seem to figure it out, can someone give me some help?
Here's the code:
String cde = "1,685";
float num = Float.valueOf(cde).floatValue();
Exception:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "1,685"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Float.valueOf(Unknown Source)
at Ascii.main(Ascii.java:8)
Thanks in advance for any help!
Regards
Pedro Pinto
> String cde = "1,685";
> float num = Float.valueOf(cde).floatValue();
You might want to look at Float.parseFloat which doesn't create
an intermediary Float object. However, that's not the problem.
The problem is the ','.
The expected format of floating point numbers uses American notation,
so the decimal point must be '.', not ','. There should be no
unnecessary characters, as, e.g., a thousands separator.
I.e., if the number you expect is 1 point something, write it as
"1.685". It it is thousand and something, write "1685".
> Exception in thread "main" java.lang.NumberFormatException: For input
> string: "1,685"
Tsk, tsk, bad error message. It could have said that it was an unexpected
','.
/L
--
Lasse Reichstein Nielsen - l...@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
First, you should use Float.parseFloat(), not valueOf().floatValue().
Second in Float.valueOf, "." is the decimal notation, not ",".
If you need to parse it in a locale specific way, look into
java.text.NumberFormat
temp = value.split(",");
value = temp[0]+"."+temp[1];
numero = Float.parseFloat(value);
I'll use the replace later to avoid all these operations.
Thanks once again
Regards
Pedro Pinto
As Daniel pointed out, you should use the NumberFormat/DecimalFormat
classes. Here's an example:
NumberFormat formatter = NumberFormat.getInstance();
float f = formatter.parse("1,685");
The getInstance method creates an instance of NumberFormat in the
current locale (my locale is Brazilian Portuguese, which uses comma to
separate decimal values, and that's why it worked). You can pass a
Locale object to specify a non-default locale.
If you need a more accurate formatting, try the DecimalFormat class.
You can construct an object of this class with a custom format.
See ya!