简体   繁体   中英

How do I validate a decimal like this 00.00?

I am learning validation expressions and have attempted to write one to check a decimal like the example below but I am having some issues.

The number to validate is like this:

00.00 (any 2 numbers, then a ., then any 2 numbers)

This is what I have:

^[0-9]{2}[.][0-9]{2}$

This expression returns false but from a tutorial I read I was under the understanding that it should be written like this:

^ = starting character 
[0-9] = any number 0-9
{2} = 2 numbers 0-9
[.] = full stop
$ = end

Use the right tool for the job. If you're parsing decimals, use decimal.TryParse instead of Regex.

string input = "00.00";
decimal d;
var parsed = Decimal.TryParse(input, out d);

If the requirement is to always have a 2 digits then a decimal point then 2 digits you could do:

var lessThan100 = d < 100m;
var twoDecimals = d % 0.01m == 0;
var allOkay = parsed && lessThan100 && twoDecimals;

So our results are

Stage       | input = "" | "abc" | "00.00" | "123" | "0.1234"
-------------------------------------------------------------
parsed      | false      | false | true    | true  | true
lessThan100 | -          | -     | true    | false | true
twoDecimals | -          | -     | true    | -     | false

Although if you really need it to be that exact format then you could do

var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var allOkay = isOkay && input.Length == 5 && input[2] == separator;

If you absolutely have to use Regex then the following works as required:

Regex.IsMatch("12.34", @"^([0-9]{2}\.[0-9]{2})$")

Regex explanation:

  • ^ - start of string
  • () - match what's inside of brackets
  • [0-9]{2} exactly 2 characters in the range 0 - 9
  • \\. - full stop (escaped)
  • $ - end of string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM