How can I set both default decimal and thousands separator for formatting number in asp.net mvc regardless of culture?
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.
string.Format("{0:N2}", yourLovelyNumber);
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
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))
variable.ToString("n2") - This worked for me in ASP.Net MVC Razor.
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)