开发者

How Can I Parse a Number Equivalent to DateTime.TryParseExact?

开发者 https://www.devze.com 2023-01-14 08:14 出处:网络
I have a requirement where the client needs to validate a bunch of excel spreadsheets. One of the validation rules is that this field must be a number that looks like \'x.xx\' (so \'3.00\' is valid, \

I have a requirement where the client needs to validate a bunch of excel spreadsheets. One of the validation rules is that this field must be a number that looks like 'x.xx' (so '3.00' is valid, '3.000' is not). This should be as easy as Doub开发者_如何学Pythonle.TryParseExact(s, "#.##", out number) but I guess it is not there. Is there a way to get this done without using regular expressions? The client is using a DSL and I don't want to make them learn regular expressions.


I suppose you could do this?

public static bool TryParseExact(string text, string format, out double value)
{
    if (double.TryParse(text, out value))
    {
        // basically, make sure that formatting the result according to the
        // specified format ends up providing the same value passed in
        return text == value.ToString(format);
    }

    return false;
}

It's just an idea; to be perfectly honest I haven't exactly thought it all the way through.

0

精彩评论

暂无评论...
验证码 换一张
取 消