سؤال

I have mask in textbox "99:99" I need convert to decimal. example: string "12:34" converted to 12.34

I create method:

private decimal ConvertStringMaskToDecimal(string strMask)
{
    var split = strMask.Split(':');
    if(split.Length==2)
    {
        decimal returnValue = decimal.Parse(split[0]) + decimal.Parse(split[1])/100;
        return returnValue;
    }
    else
    {
        throw new ArgumentException("strMask not valid");
    }
}

this code is worked but I think the code is not correct, how to solve this problem

هل كانت مفيدة؟

المحلول

Just replace the : with . before parsing:

decimal.Parse(strMask.Replace(':', '.'), CultureInfo.InvariantCulture)

Note the use of CultureInfo.InvariantCulture to ensure that the . is interpreted correctly.

نصائح أخرى

As I remarked in my comment to Oded's answer: hardcoding a dot as a decimal separator is not recommended.

This picture explains why.

I suggest:

using System.Globalization;

// (...)
decimal.Parse(strMask.Replace(":", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator));

instead.

Or, as Henk Holterman suggested:

decimal.Parse(strMask.Replace(':', '.'), CultureInfo.InvariantCulture);

To the same effect (not crashing on non-American machines).

you can use decimal.Parse after replacing colon : with the decimal point .

decimal.Parse(strMask.Replace(':', '.'), CultureInfo.InvariantCulture)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top