2

OK. I know that according to Java Docs:

parseFloat will return a NumberFormatException - if the string does not contain a parsable float.

I thought that the parseFloat method would see if the first character is a number and if it is then it will read until it finds a character and then return the value up until but not including the character as a Float.

So with that in mind I am attempting to do the following and getting a NumberFormatException.

float value;

value = Float.parseFloat("50C");

I was hoping that it would return with value = 50.

Can someone please explain why the above conversion would return a NumberFormatException? Did I misunderstand what the parseFloat would do?

3 Answers3

4

According to the Java 7 docs on Float:

parseFloat(String s)

Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.

And for the valueOf method:

valueOf(String s)

Returns a Float object holding the float value represented by the argument string s.

So if the string passed to parseFloat method does not represent a float string, you will end up getting your NumberFormatException because it cannot convert it to a float.

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html

Community
  • 1
  • 1
Matt Davis
  • 470
  • 5
  • 16
2

50C is not a parseable float only f, F,d,D are allowed.

Try:

value = Float.parseFloat("50f");
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
2

The issue is that 50C cannot be parsed by the standard library as float number and hence the exception. To make it a float parseable you need to add character like F or f like 50f or 50F.

alf
  • 8,377
  • 24
  • 45
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331