0

In asp mvc I have an input text control that must accept a double number.

I have customized the jQuery validation plugin to accept number with . and , separator and written a custom DecimalBinder:

public class DecimalModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDouble(valueResult.AttemptedValue, CultureInfo.InvariantCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}

The problem is that if in the input text control I write, for example, "3,3" the

actualValue = Convert.ToDouble(valueResult.AttemptedValue, CultureInfo.InvariantCulture);

give me the value "33" and, instead, I want 3.3.

When I inspect the modelState I see

enter image description here

Why actualValue is "33" instead of "3.3" if i use InvariantCulture?

George Lanetz
  • 300
  • 5
  • 18
Tom
  • 4,007
  • 24
  • 69
  • 105

1 Answers1

2

That is because 3,3 converted to a double using the InvariantCulture yields 33. It does not make the output to become in the InvariantCulture, since the numeric data type double has nothing to do with a specific culture. Only the textual representation does.

So 3,3 is not a valid value for a string to be converted to a double. It removes the , and converts to 33. 3.3 would be a valid value to be converted to 3.3d. So you have to use another culture, probably it-IT as in your debug view, to convert the value 3,3 to a double of 3.3d.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325