Does anybody know why the following snippet does not throw a NumberFormatException
?
public class FlIndeed {
public static void main(String[] args) {
System.out.println(new FlIndeed().parseFloat("0xabcP2f"));
}
public float parseFloat(String s) {
float f = 0.0f;
try {
f = Float.valueOf(s).floatValue();
return f;
}
catch (NumberFormatException nfe) {
System.out.println("Invalid input " + s);
}
finally {
System.out.println("It's time to get some rest");
return f;
}
}
}
Note that there is a P inside .parseFloat("0xabcP2f"));
Converts the string representation of a number to its double-precision floating-point number equivalent. Parse(String, NumberStyles)
parseDouble() We can parse String to double using parseDouble() method.
The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number.
The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn't in a valid format, Parse throws an exception, but TryParse returns false .
Because it do accept hexadecimal values and you are passing a valid hexadecimal value.
From Doc (s = input String argument)
s should constitute a FloatValue as described by the lexical syntax rules:
FloatValue: Signopt NaN Signopt Infinity Signopt FloatingPointLiteral Signopt HexFloatingPointLiteral SignedInteger HexFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffixopt HexSignificand: HexNumeral HexNumeral . 0x HexDigitsopt . HexDigits 0X HexDigitsopt . HexDigits BinaryExponent: BinaryExponentIndicator SignedInteger BinaryExponentIndicator: p P
about NumberFormatException
thrown from valueOf
where Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger and FloatTypeSuffix are as defined in the lexical structure sections of the of the Java Language Specification. If s does not have the form of a FloatValue, then a NumberFormatException is thrown.
About use of p in hex: P in constant declaration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With