asp.net mvc set number format default decimal thousands separators

前端 未结 7 1579
闹比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:27

    I had the same issue and can recommend autoNumeric plugin https://github.com/autoNumeric/autoNumeric

    Include plugin:

    <script src="~/Scripts/autoNumeric/autoNumeric.min.js" type="text/javascript"></script>
    

    Html:

     <input type="text" id="DEMO" data-a-sign="" data-a-dec="," data-a-sep="." class="form-control"> 
    

    Script:

    <script>
     jQuery(function($) {
    $('#DEMO').autoNumeric('init');   
     });
    </script>
    

    You can type only number, if you type 100000,99 you will see 100.000,99.

    0 讨论(0)
  • 2020-12-12 00:32
    string.Format("{0:N2}", yourLovelyNumber);
    
    0 讨论(0)
  • 2020-12-12 00:34

    You need to specify a custom number format in order to achieve what you are looking for. Here is the MSDN on creating custom string formatting functions.

    If you really need a custom thousands separator, create your own NumberFormatInfo variable assigning the values that you want to the thousands separator (and the decimal if so needed). Then apply the custom format to your number.

    var numberFormatter = new CultureInfo( "en-US", false ).NumberFormat;
    numberFormat.NumberDecimalSeparator = ";";
    numberFormat.NumberGroupSeparator = "-";
    var myNumber = 1234567.89;
    var myFormattedNumber = myNumber.ToString("#,###.##", numberFormatter);
    
    //myFormattedNumber -> 1-234-567;89
    

    Some information on the NumberFormat class from the MSDN

    0 讨论(0)
  • 2020-12-12 00:34

    I will post the code that finally worked for me. On controller, on OnActionExecuting function:

    ViewBag.CurrentNumberFormat = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
    ViewBag.CurrentNumberFormat.NumberDecimalDigits = 2;
    ViewBag.CurrentNumberFormat.NumberDecimalSeparator = "~";
    ViewBag.CurrentNumberFormat.NumberGroupSeparator = " ";
    

    and in View:

     @((1234567.435).ToString("#,###.##", ViewBag.CurrentNumberFormat))
    
    0 讨论(0)
  • 2020-12-12 00:39

    variable.ToString("n2") - This worked for me in ASP.Net MVC Razor.

    0 讨论(0)
  • 2020-12-12 00:52

    You could create a DisplayTemplate that would handle how numbers like this are displayed in your views:

    /Views/Shared/DisplayTemplates/float.cshmtl:

    @model float
    @string.Format("{0:N2}", Model);
    

    and then you can call it like this from your views, if Amount was of type float:

    @Html.DisplayFor(m => m.Amount)
    
    0 讨论(0)
提交回复
热议问题