MVC3 - 带前导零的 double 类型的小数点后 3 位 [英] MVC3 - 3 decimal places on type double with leading zero

查看:17
本文介绍了MVC3 - 带前导零的 double 类型的小数点后 3 位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字段用于以公斤为单位的重量(键入 double 或使用其他内容??).在编辑视图中,我希望用户输入千位的数字.在显示视图中,我希望 Kgs 显示为 560.250

I have a field for weight in Kgs (type double or use something else??). In edit view I would like the user to enter numbers to the thousandth place. In display view I would like the Kgs to appear like 560.250

尝试学习MVC3 + Razor.愿意探索 JQuery、正则表达式的使用、验证器、视图模板、视图模型......

Trying to learn MVC3 + Razor. Willing to explore JQuery, use of regular expressions, validators, view templates, view models...

MVC 基于约定的魔力"需要习惯.对使用哪种方法感到困惑.

The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.

预先感谢您的帮助.

推荐答案

你可以在你的视图模型上使用数据注解:

You could use data annotations on your view model:

[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Weight { get; set; }

在你看来

@Html.EditorFor(x => x.Weight)

将正确格式化输入字段中的值.

will properly format the value in the input field.

另一种可能是为 double 类型编写自定义编辑器模板 (~/Views/Shared/EditorTemplates/double.cshtml):

Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):

@model double?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")

然后在您看来:

@Html.EditorFor(x => x.Weight)

或者如果您不想覆盖应用程序中所有双精度类型的所有模板,您可以将其放入一些自定义模板位置,例如 ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml 和那么在您看来:

or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:

@Html.EditorFor(x => x.Weight, "MyFormattedDouble")

我个人更喜欢第一种方法,它使用数据注释来控制双精度值的格式.

Personally I prefer the first approach which uses data annotations to control the format of the double values.

这篇关于MVC3 - 带前导零的 double 类型的小数点后 3 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆