Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept comma and dot as decimal separator [duplicate]

Tags:

Model binding in ASP.NET MVC is great, but it follows locale settings. In my locale decimal separator is comma (','), but users use dot ('.') too, because they are lazy to switch layouts. I want this implemented in one place for all decimal fields in my models.

Should I implement my own Value Provider (or event Model Binder) for decimal type or I've missed some simple way to do this?

like image 644
artvolk Avatar asked Jan 18 '13 14:01

artvolk


People also ask

How do you make Excel accept dots instead of commas?

Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes.

How do I change the Decimal separator in PowerPoint?

Unfortunately, you cannot change the decimal separator just for PowerPoint. PowerPoint uses the separators defined in the operating system for the language region. Changing them requires changes that are permanent and system-wide.

How do I change commas to dots in Excel Windows 10?

go to Start > Control Panel > Regional and Language Options | Windows 10 (Start >type Control Panel and press enter > Region) Click Additional Settings. For Decimal Symbol, enter a dot: .


1 Answers

Cleanest way is to implement your own model binder

public class DecimalModelBinder : DefaultModelBinder {     public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)     {         var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);          return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue);         // of course replace with your custom conversion logic     }     } 

And register it inside Application_Start():

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder()); 

Credits : Default ASP.NET MVC 3 model binder doesn't bind decimal properties

like image 124
mathieu Avatar answered Oct 12 '22 04:10

mathieu