Decimal troubles in aspnet core / ef core entity

741 views Asked by At

My website has a form with a number input that takes decimal numbers. This is sent back to the controller in a viewmodel. When validation passes, the viewmodel is converted to an entity like this:

quotation.WidthMeters = model.WidthMeters.

So here is where the fun starts.

My website is in the Dutch culture. We use comma for decimal seperators. So the user inputs 2,40 in the form. This is sent back. I can see that the data in the viewmodel contains 2.40 which is the US way of saying 2,40. Now when this value is assigned to the entity, it all of a sudden changes to 240. So quotation.WidthMeters is now 240, but the property assigning it (model.WithMeters) is 2.40.

Why?

(probably important to add: I made my controller run in the InvariantCulture by adding the following two lines to the constructor of the controller:

Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

The entity is in the same project)

update

When I add the following to my startup.cs, it works:

app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            SupportedCultures = new [] {new CultureInfo("en-US") },
            SupportedUICultures = new [] { new CultureInfo("en-US") }
        });

It doesn't work when I change the culture to nl-NL, however I prefer using the Dutch culture since that will also fix the dates.

update 2

In my form I used the <input type="number" /> field which at least in Chrome and Firefox always send the number back with a decimal point. I switched back to a textfield and changed the cultures to nl-NL. Now I can enter the numbers with decimal comma and it is handled correctly by the server.

So TRWTF is, Why does a browser show a comma in the number field but send it back with a dot?

1

There are 1 answers

1
Bjarke M On

It doesn't sound correct. You should double check your types in the assignment and also their values (e.g. in the debugger). It just doesn't make sense that assigning a decimal to another decimal in the .NET runtime will change the value.