asp.net mvc set number format default decimal thousands separators

前端 未结 7 1594
闹比i
闹比i 2020-12-12 00:25

How can I set both default decimal and thousands separator for formatting number in asp.net mvc regardless of culture?

7条回答
  •  生来不讨喜
    2020-12-12 00:54

    To control the thousands separator you'll have to apply your changes to the NumberFormat for the current culture.

    If you want this to happen regardless of the current culture you can simply clone the current culture, apply your modified NumberFormat and set it as the current one.

    In an MVC app you would typically do this during Application_BeginRequest

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        newCulture.NumberFormat.NumberGroupSeparator = "~";
    
        System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
        System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;
    }
    

    Now you can use the 'normal' formatting options of ToString() to further control the formatting according to your needs:

    var a = 3000.5;
    var s = a.ToString('N:2') // 3~000.50
    s = a.ToString('N:4') // 3~000.5000
    

提交回复
热议问题