Home » Jquery » c# – How to pull the correct decimal format from the database when the browser is not on an en-US english operating system

c# – How to pull the correct decimal format from the database when the browser is not on an en-US english operating system

Posted by: admin February 22, 2020 Leave a comment

Questions:

Default EditorFor() declares the input field as text and loads the value from the database fine, but displays it with a coma as a separator because the browser is running on non US version of Windows and upon validation of the form it fails on that field if it hasn’t been changed and/or someone types in a decimal number with a coma instead of a dot.

If I define the field as number I get a warning in the console:

@Html.EditorFor(m => m.DecimalNumber, new { htmlAttributes = new { @class = "form-control", @type="number" } })

gives

jquery-3.4.1.js:4817 The specified value "0,00" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?

The number is proper decimal(18, 4) in the database, using entity framework 6 it’s also set as such in the model, I haven’t set the Web.Config globalization settings, and I don’t know what changes the dot into a coma. I can type in decimal numbers with either dots or comas as separators, and jquery validate is happy with either.

How can I get the value loaded in the field when the form loads? I tried adding the @lang=”en” attribute in the Editor constructor, but it didn’t make any difference either.

How to&Answer:

I’m tried this solution for me and it’s work fine :

1 – Convert DecimalNumber to string by including culture in the front :

<div>
    @{
        var stringNumber = Model.DecimalNumber.ToString("f2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"));
        @Html.EditorFor(m => stringNumber)
    }
</div>

2 – Parsing string to decimal in the server side :

public ActionResult Create(string stringNumber)
{
    decimal decimaNumber;
    if (decimal.TryParse(stringNumber, NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out decimaNumber))
    {
        if(decimaNumber > 0)
        {
            // use decimal number here
        }
    }
    return View();
}

I hope that will help you out.