简体   繁体   中英

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 (ie 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 in 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);

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