question

martin.j avatar image
0 Likes"
martin.j asked Jordan Johnson answered

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

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.

FlexSim 22.2.0
stringconversionisdigitisnumeric
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Jordan Johnson avatar image
2 Likes"
Jordan Johnson answered

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.

5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Lars Jacobsen avatar image
0 Likes"
Lars Jacobsen answered Felix Möhlmann commented

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



1661174081057.png (9.4 KiB)
· 1
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Felix Möhlmann avatar image Felix Möhlmann commented ·

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[i] >= 48 && test[i] <= 57)
{
    // char is numerical
}

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

0 Likes 0 ·