GetNumericValue has a very weird behaviour.

GetNumericValue has a very weird behaviour.
Consider this code:

uses Character;

//...

procedure TForm1.cxButton1Click(Sender: TObject);
var S: String;
begin
  S := 'Test';
  ShowMessage( FloatToStr( GetNumericValue( S [ 1 ] ) ) );
end;

It always returns -1 .
I am working on Windows 7 x64 - Delphi XE .

Anybody experiencing the same? Something obvious I am missing?

Regards,

A

Comments

  1. Would you rather it threw an exception?  "Test" should return something like NAN (Not A Number) or bomb with some sort of numeric conversion exception.  GetNumericValue is being nice and returning -1 since it probably can't return NAN.  Have you considered using Val() instead and checking the error position?

    ReplyDelete
  2. Hang on a minute, I thought that routine was returning a character ORDINAL in the string. It should return the correct value in my opinion! And yes, I would prefer an exception :-)

    ReplyDelete
  3. If you want the ordinal value of "T" then there are less Rube Goldberg methods of calculating it :-)

    http://en.wikipedia.org/wiki/Rube_Goldberg_machine

    Try to avoid exceptions, especially in places where humans are doing the data input.  Val(S, MyNumber, ErrorPosition) is a better way of translating strings (good or garbage) into numbers without exceptions.  If ErrorPosition returns as non-zero, then you can politely tell the user that he/she needs some typing lessons.

    ReplyDelete
  4. Am I missing something here, or is 54 (yes, that is base 16 :D) what you expected when calling the function on "T"? If yes: Ord() is your friend. If no: Ignore this message.

    ReplyDelete
  5. As far as I can tell from CodeInsight, ORD and CHR only work for byte-wide values of CHAR.
    CodeInsight might be misleading though.

    A

    ReplyDelete
  6. It could be because 'T' is not in the numeric category for UTF-16.

    At least that is my interpretation of http://docwiki.embarcadero.com/Libraries/XE2/en/System.Character.TCharacter.GetNumericValue

    ReplyDelete

Post a Comment