0

For getting the float value from the webform (client-side event), I do use the code like:

var price = parseFloat(s.GetText());
if (!isNaN(price)) {
    // calculate the related values
}

It works fine when the user enters a number (correctly). The isNaN() works detects fine also the situation when the user types a string instead of a number (that is, when the first character does not belong to a number).

When the user types the value like 5 x, the 5 is converted correctly because the parser stops on x, and ignores the existence of the x. So, the unwanted string after the number is not detected. However, storing the field content 5 x into the database fails -- because the other code of the web page parses the value differently, and it requires it to be a number and nothing more.

How would you implement the check?

pepr
  • 20,112
  • 15
  • 76
  • 139
  • Stringify the parsed number and check it matches the inputted string? – spender May 10 '22 at 11:46
  • @spender - That'll break on lots of things though. Extra leading zeros on the input, the string going to scientific notation, ... – T.J. Crowder May 10 '22 at 11:48
  • maybe you'll find lots of inspiration from here: https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number – Diego D May 10 '22 at 11:48
  • 1
    For this reason, I don't use `parseFloat` nearly ever. I have a `parseNumber` function that uses a conversion using the full string (e.g., `+str` or `Number(str)`, handling the case where `""` would be considered `0` beforehand: `const parseNumber = (str) => str ? +str : NaN;` [This answer](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875) (one of mine) describes various ways you can parse strings to numbers. – T.J. Crowder May 10 '22 at 11:51

0 Answers0