Priya
Priya

Reputation: 21

TextBox display with 2digit decimal value in MVC3 Razor

The textbox decimal value has this format "0,0000" (, is the decimal separator). I'd like have only 2 decimal. How can I do this ?

My model has:

 [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
    public decimal DisplayOrder { get; set; }

View:

@Html.EditorFor(model => model.DisplayOrder)

But it doesn't works

Thanks in advance

Upvotes: 2

Views: 2463

Answers (2)

Mohamed Rozza
Mohamed Rozza

Reputation: 567

You may refer to this topic for more info about decimal format in MVC3 Decimal Format in asp.net mvc3

And this link for a similar problem Formatting decimal in asp.net mvc3

If none of the above worked you can try converting your number to string and passing it to this function.

 /// <summary>
    /// Formatting a given number to 0,00
    /// </summary>
    /// <param name="number"></param>
    /// <returns></returns>
    string NumberFormatting(string number)
    {
        if (number.Contains(','))
        {
            string[] str = number.Split(',');
            if (str[1].Length == 1)
            {
                number += "0";
            }
        }
        else
        {
            number += ",00";
        }
        return DecreaseNumberDigits(number);
    }

    /// <summary>
    /// To allow only two digits after the decimal mark
    /// </summary>
    /// <param name="number"></param>
    /// <returns></returns>
    string DecreaseNumberDigits(string number)
    {
        if (number.Contains(','))
        {
            string[] str = number.Split(',');
            if (str[1].Length > 2)
                number = str[0] + "," + str[1].ToCharArray()[0].ToString() + str[1].ToCharArray()[1].ToString();
        }
        return number;
    }

Upvotes: 3

Sampath
Sampath

Reputation: 65978

You can use regular expression for do your job.

Try like below.

[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price must can't have more than 2 decimal places")]
public decimal DisplayOrder { get; set; }

For more information check Regular Expression Library Here

I hope this will help to you.

Upvotes: 0

Related Questions