Is there a way to test if a string/char is numeric

Is there a way to test if a string/char is numeric

MBJEBZSRG
Advocate Advocate
31 Views
3 Replies
Message 1 of 4

Is there a way to test if a string/char is numeric

MBJEBZSRG
Advocate
Advocate

[ FlexSim 22.2.0 ]

I have been looking for a way to test if a string or character is a digit or alphanumeric value. In most programming languages there is a function called IsDigit, IsNumeric or something similar, but I cant find that feature in flexscript.

I can use the stringtonum or .tonum methods, but since they always return 0 which is a numeric value rather than NULL, that is rather unhelpfull and a bit of an error in my opinion. You cant tell if the character you converted was actually a 0 or any other character that isnt numeric.

This would be rather usefull when trying to rename autogenerated objects that automatically get a number at the end of their name. I want to find out how many characters the numer at the end of the name is and then replace it with a code of my own choosing.

0 Likes
Accepted solutions (1)
32 Views
3 Replies
Replies (3)
Message 2 of 4

lars_jacobsen_ScandiSim
Advocate
Advocate

A possibility is to cast the string in question to a Variant. That provides some opportunities for testing the datatype. See Variant Doc

Example code


1661174081057.png


0 Likes
Message 3 of 4

moehlmann_fe
Observer
Observer

If the string only consists of ASCII characters, you can check each one by comparing it to the relevant range of ASCII indexes with the [] operator.

if(str >= 48 && test <= 57)
{
    // char is numerical
}

For the purpose of removing/replacing numbers in an autogenerated name, the replace() method could be useful.

0 Likes
Message 4 of 4

JordanLJohnson
Autodesk
Autodesk
Accepted solution

If you want to split text from a number, I'd do that with a regex:

string name = "Processor23";
var matches = name.match(/(.*[^\d])(\d+)$/);
Array parts;
while ((parts = matches.findNextMatch()).length) {
  print("whole match:", parts[1]);
  print("name:", parts[2]);
  print("number:", parts[3]);
}

I often use https://regex101.com/ to help me get the regex right.

If you use code like the code above, you can strip off the number from the name part, and then combine the name with some other value.

As far as generally testing a string to see if it is a number, I'd probably use code like this:

string test = "123.4";
if (test.match(/^[+-]?([0-9]*[.])?[0-9]+$/).length) {
  return "isNumber";
} else {
  return "not a number";
}

You could improve this regex to include scientific notation, if needed.

.


Jordan Johnson
Principal Software Engineer
>