I have a input field that looks like this
<td><input type="text" onchange="changesUnSaved()" pattern="[0-9,]{0,4}" title="Lorum ipsum" value="@(Model.EstablishmentWeeks.Single(x => x.WeekNumber == weekNum && x.Year == currentYear).Hours / 40.0)" name="amountOfFTE"></td>
This input field is used to call a function that expects a float.
The function looks like this:
public IActionResult UpdateEstablishmentWeeks(int esteblishmentId, int currentYear, int weekNum, float amountOfFTE)
On my local environment if I enter a decimal number for example 25,5 the comma in the value is kept and the result is 25,5
But after I published the code to a production environment, I noticed something strange.
On the production environment if I enter a decimal number for example 25,5 the comma in the value is removed and the result is 255
I think it has something to do with my browser, but I'm not sure. Does anybody know a solution to this problem?
CodePudding user response:
This is a culture/locale problem. On your local computer you probably have a locale with comma fraction digits separator (German, Russian, etc.). In this case, when backend gets "25,5", it binds it to the model by parsing with the current culture, which gives you 25.5 in result.
However, it looks like production environment has a dot fraction digits separator (English for example), and comma thousands separator. So when backend gets string "25,5", it parse it with english locale, which gives you the number 255 in result.
There is no one silver bullet, how to treat culture/locale specific things in the app. It includes several strategies with their own pros and cons. Examples of it could be:
- locking both frontent and backend to CultureInvariant number formats (https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#globalization-behavior-of-model-binding-route-data-and-query-strings)
- setting up binding locale based on client location/chosen language and expect client to enter numbers in format of their culture
- expecting that number could be entered with comma or dot, and trying to bind it both way choosing best result in each situation
- and others