-2

How can I check for a comma in a number?

Lets assume I have a string which represents a polynomial term that looks like this

string x = "x+1+5,54";

Now the user wants to put in and add a comma which will then be "x1+5,54," which is not a number anymore. How can I check this with an if ?

Something like if the last number already contains a comma don't append another one.

ASh
  • 34,632
  • 9
  • 60
  • 82
  • you can use regular expression https://stackoverflow.com/questions/11009320/validate-mathematical-expressions-using-regular-expression if you use ',' as a decimal separator only change regex from example to ^([-+/*]\d+(,\d+)?)* – Dzianis Karpuk Apr 07 '20 at 19:33
  • I would recommend looking for a 3rd party library that can parse formulas from strings to validate them, rather than implementing it yourself. – JamesFaix Apr 07 '20 at 19:54
  • @DzianisKarpuk how to use this regex to filter for comma? – DataLordDev Apr 07 '20 at 20:01
  • If there are characters in the string that render it invalid for your purposes, what _exactly_ is your criteria for deciding which characters are invalid? Removing the characters is easy. Knowing which ones the user didn't intend to be part of a legitimate number, not so much. Please improve your question so that you've explained clearly and precisely what the rules are here, and what _specifically_ you are having trouble with implementing. – Peter Duniho Apr 07 '20 at 20:12
  • You should use an expression parser which generates an expression tree. This way you can validate each operand individually. This is the best to parse or calculate equations. – BionicCode Apr 07 '20 at 21:19
  • @PeterDuniho to make it easy I want to know how I can get this string --> "x+1+5,54," to this "x+1+5,54" – DataLordDev Apr 08 '20 at 15:32

1 Answers1

0

Use regular expression.

        if (Regex.IsMatch(a, @"^((\d+,?\d*)|(\w?))([-+/]((\d+,?\d*)|(\w?)))*$"))
        {
            //correct
        }
        else
        {
            //incorrect
        }

You'll get false, when user inputs extra comma, so you can handle it.