Search code examples
c#type-conversionmaskedtextbox

How convert string (masked) to decimal?


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


Solution

  • 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.