Page 1 of 1
function IsNumeric()
Posted: Tue Jul 11, 2023 12:01 pm
by Barbie
Has anyone a function IsNumeric() handy? I don't want to reinvent the wheel…
NXPUtil.IsNumeric() does not respect the dot.
The function should recognise the following example strings as numeric (too lazy to create a regex for this):
1.23
1
+1
+1.23
-1
-1.23
Cherry on ice would be returning the value also:
function bool IsNumeric(coerce s as string, Optional out float value)
Re: function IsNumeric()
Posted: Tue Jul 11, 2023 1:33 pm
by snowguy
Re: function IsNumeric()
Posted: Tue Jul 11, 2023 4:56 pm
by Buggie
Code: Select all
f = float(s);
ret = f != 0;
if (!ret) {
// do some simple checks if need distinguish false and 0 value as input.
}
return ret;
Side effect it accept values like "12345 some text".
If you not need it, you can later check Something like that:
if (float(s) == float(s $ "9999")) die("Bad chars at end");
OFC in some edge cases like "1.00000000" it make false positive, but it good enough for most cases.
Can be improved as:
Code: Select all
f = float(s);
return f != 0 || f != float(s $ "999");
Or even:
Code: Select all
f = float(s);
return f != float(s $ "999");
Fit for most cases. except some really edge cases, when numbers specified too precise for float so append at end not change it.
Re: function IsNumeric()
Posted: Thu Jul 13, 2023 1:40 pm
by PrinceOfFunky
Convert the String to float, then the resulting float back to String and compare the two strings, if they are equal it's numeric.
Re: function IsNumeric()
Posted: Thu Jul 13, 2023 6:52 pm
by Barbie
PrinceOfFunky wrote: ↑Thu Jul 13, 2023 1:40 pm
Convert the String to float, then the resulting float back to String and compare the two strings, if they are equal it's numeric.
Thanks, but string(float("1.23")) is something like "1.2300000" AFAIR. I already run into such.
Re: function IsNumeric()
Posted: Tue Oct 03, 2023 5:43 pm
by PrinceOfFunky
Barbie wrote: ↑Thu Jul 13, 2023 6:52 pm
PrinceOfFunky wrote: ↑Thu Jul 13, 2023 1:40 pm
Convert the String to float, then the resulting float back to String and compare the two strings, if they are equal it's numeric.
Thanks, but string(float("1.23")) is something like "1.2300000" AFAIR. I already run into such.
Then just compare the same amount of characters, like left(x, strLen(x)) and left(y, strLen(x)).
Re: function IsNumeric()
Posted: Tue Oct 17, 2023 7:57 am
by ExpEM
Have you got a working solution?
It wouldn't be an ideal way but you could parse the string one char at a time.
Code: Select all
Psudo code.
While loop
if first char in string
if char = (+,-,.,0,1,2,3,4,5,6,7,8,9)
Keep going
else
return false
else
if char = (.,0,1,2,3,4,5,6,7,8,9 and "." hasn't already occurred)
Keep going
else
return false
if no more char
return true
else
next char