Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I cant send Decimal variable properly (with '.' or ',')

Here is my DiscountRate variable in my model.

 public decimal DiscountRate { get; set; }

Here is my input in view.

 @Html.TextBoxFor(x=>x.DiscountRate, new {  @class = "form-control", @type = "number", step = "0.01", @placeholder = "0.00", @min="0", @max="100" })

The problem is when I enter a value (2,50 or 2.50 etc.) I catch it in my Controller like 250. What is the problem here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your issue stems from the HTML5 type="number" input not correctly handling dot . and comma , in different browsers and culture settings. As a result, when you enter 2,50 or 2.50, it is sent to the server as 250.

To fix this, change the input type to text and handle the validation on the server side:

@Html.TextBoxFor(x => x.DiscountRate, new { @class = "form-control", @placeholder = "0.00" })

Also, ensure that your application’s culture settings are configured properly:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

Yes, you can continue using the "number" property, but you’ll need to make some adjustments. This is important because decimal separators vary between cultures.

One solution is to add the lang and step attributes to your input element. By setting the lang attribute to "en", you ensure that the decimal separator is a dot .:

@Html.TextBoxFor(x => x.DiscountRate, new { @class = "form-control", @type = "number", @lang = "en", step = "0.01", @placeholder = "0.00", @min = "0", @max = "100" })

Additionally, you can use JavaScript on the client side to replace comma , with dot .:

<script>
    document.getElementById("DiscountRate").addEventListener("input", function (e) {
        this.value = this.value.replace(',', '.');
    });
</script>

This way, regardless of whether the user enters a comma or a dot, the value will be transmitted correctly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading