Why can this floating-point text value be parsed as double?

Does anyone 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 time to get some rest"); return f; } } } 

Note that inside .parseFloat("0xabcP2f"));

is P,
+6
source share
3 answers

Because it accepts hexadecimal values, and you pass the actual hexadecimal value.

From Doc (s = String input argument)

s must be a FloatValue, as described in the lexical syntax of the rule:

  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 selected from valueOf

where Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger and FloatTypeSuffix are defined in the sections of the lexical structure of the Java Language Specification. If s does not have a form from FloatValue, then a NumberFormatException is thrown.

About using p in hexadecimal: P in the declaration of constants

+7
source
  System.out.println(new FlIndeed().parseFloat("0xabcP2f")); 

0xabcP2f - The value of HexSignificand, which is legal for Float.valueOf ("0xabcP2f"). Therefore it does not throw any exceptions

See http://docs.oracle.com/javase/6/docs/api/java/lang/Float.html#valueOf%28java.lang.String%29 for details

+3
source

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

If m is a float value with a normalized representation, substrings are used to represent value and exponent fields. Significance is represented by the characters "0x1". followed by a lowercase hexadecimal representation of the rest of the value as a fractional part. Trailing zeros in the hexadecimal representation are deleted if all digits are not equal to zero, in which case one zero is used. Next, the metric is represented by “p,” followed by a decimal string of the unbiased metric , as if it were called by calling Integer.toString on the exponent metric.

Thus, it is used to denote the exponent in the hexadecimal string that you entered, this is a perfectly legitimate part of the hexadecimal string, so there is no parsing error and no NumberFormatException .

+2
source

All Articles