2

I'm getting crazy with decimal places in asp.net core.

Sql Server table:

money decimal (18,0)   

I put in Startup.cs /Configure

var cultureInfo = new CultureInfo("vi-VN");
        cultureInfo.NumberFormat.CurrencySymbol = "đ";
        cultureInfo.NumberFormat.CurrencyDecimalDigits = 0;
        cultureInfo.NumberFormat.CurrencyDecimalSeparator = ",";
        cultureInfo.NumberFormat.CurrencyGroupSeparator = ".";


        CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
        CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

        var supportedCultures = new[]
        {
            cultureInfo
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("vi-VN"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

However, when I get any decimal value, it's always in 2 decimal places.

On View:

<input asp-for="money"/> => show something like 123455,00. and this value will be submitted back to the controller for calculation, so it should be in numeric format, not in string format like ToString("N0")...

nam vo
  • 3,271
  • 12
  • 49
  • 76

1 Answers1

0

The Decimal's ToString is a indeed weird in this aspect, as it does not have any consistent return. It returns as many decimals available in the original number, and if it has no decimals, it just returns the whole number without decimals.

You will need to use C format specifier, to indicate that this is a monetary number, and that it should follow the culture specified in the thread.

decimal x = 100.5555;
Console.Write(x.ToString("C")); // Outputs 101 đ. Uses away from zero roundign.
Console.Write(x.ToString()); // Outputs 100.5555.

For more information, please visit: Standard Numeric Format Strings.

Edit:

To work with the ModelBinder, you can specify the format using data annotations on the view model itself. See here: "asp-format" not applied to tag helpers.

Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44
  • The problem is when you bind model to view , it must be a number so that later the value returns to controller for calculation. – nam vo Sep 07 '17 at 04:42
  • You can use data annotations for that. Check the edit. – Ghasan غسان Sep 07 '17 at 05:55
  • data annotations wont work, validation system will generate "This is not a number" etc. Many complains here https://stackoverflow.com/questions/39737607/aspnet-core-decimal-binding-not-working-on-non-english-culture or here https://github.com/aspnet/Mvc/issues/5331 – nam vo Sep 19 '17 at 07:39