3

无论文化如何,如何在 asp.net mvc 中为格式化数字设置默认的十进制和千位分隔符?

4

7 回答 7

5

您可以创建一个DisplayTemplate来处理这样的数字在您的视图中如何显示:

/Views/Shared/DisplayTemplates/float.cshmtl

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

然后你可以从你的观点中这样称呼它,如果Amount是类型float

@Html.DisplayFor(m => m.Amount)
于 2012-10-26T11:59:37.603 回答
3

您需要指定自定义数字格式才能实现您要查找的内容。 这是关于创建自定义字符串格式化函数的 MSDN 。

如果您确实需要自定义千位分隔符,请创建您自己的 NumberFormatInfo 变量,将您想要的值分配给千位分隔符(如果需要,还可以使用小数)。然后将自定义格式应用于您的号码。

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

MSDN 中有关 NumberFormat 类的一些信息

于 2012-10-26T14:10:54.797 回答
3

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
于 2012-10-26T14:03:24.430 回答
2

variable.ToString("n2") - 这在 ASP.Net MVC Razor 中对我有用。

于 2013-05-14T15:35:19.370 回答
1
string.Format("{0:N2}", yourLovelyNumber);
于 2012-10-26T11:57:22.330 回答
0

我将发布最终对我有用的代码。在控制器上,在 OnActionExecuting 函数上:

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

在视图中:

 @((1234567.435).ToString("#,###.##", ViewBag.CurrentNumberFormat))
于 2012-10-29T11:10:37.430 回答
0

我有同样的问题,可以推荐autoNumeric插件https://github.com/autoNumeric/autoNumeric

包括插件:

<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>
 jQuery(function($) {
$('#DEMO').autoNumeric('init');   
 });
</script>

您只能输入数字,如果您输入 100000,99,您将看到 100.000,99。

于 2017-09-01T13:38:41.223 回答