Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"));

like image 289
Rollerball Avatar asked Mar 08 '13 11:03

Rollerball


People also ask

What does double parse mean?

Converts the string representation of a number to its double-precision floating-point number equivalent. Parse(String, NumberStyles)

What is the method used for parsing a value into a double?

parseDouble() We can parse String to double using parseDouble() method.

What does float parse do?

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.

How does parse work in C#?

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 .


1 Answers

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

like image 183
Ajinkya Avatar answered Oct 04 '22 19:10

Ajinkya