user5545268
user5545268

Reputation: 25

Float.parseFloat returns NumberFormatException that does not make sense

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?

Upvotes: 2

Views: 1890

Answers (3)

thegauravmahawar
thegauravmahawar

Reputation: 2823

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

Try:

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

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172518

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.

Upvotes: 2

Matt Davis
Matt Davis

Reputation: 470

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

Upvotes: 4

Related Questions