开发者

Validate whether a double/decimal is currency C#

I am reading in a pipe delimited file and need to check whether a column is a valid currency (i.e. it must follow a format as xxxxx.xx , so a maximum of two digits after the decimal although it is not necessary to have any digits after the decimal). How would I go about doing this i开发者_JAVA技巧n C#?


Try converting your value to a currency, like this:

double dummy;
bool valid = double.TryParse(value, NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"), out dummy);

valid will then be either true if TryParse could parse it as a currency. This is by far a better option than using regular expressions.

To get the fraction (decimals) of your value, just convert it to an int and subtract it from the original value, like:

double fraction = value - (int)value;

fraction will then contain decimals and you can do whatever you like with them.


You could use a regular expression:

using System.Text.RegularExpressions;

if (Regex.IsMatch(myString, @"\d+(\.\d{1,2})?"))
{
    // ...
}

or use decimal.TryParse() if you just want to check that you can convert it to a decimal:

decimal value;
if (decimal.TryParse(myString, out value))
{
    // Do something with value
}


looks a bit hacky, but interesting way to ensure that you've parsed money correct:

float amount = float.TryParse("$1,200,000.34", NumberStyles.Currency);

bool fractionLooksFine = (new System.Version((amount*100).ToString()).Minor == 0);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜