代码之家  ›  专栏  ›  技术社区  ›  Alfred Wallace

更有效地格式化货币值的方法

  •  2
  • Alfred Wallace  · 技术社区  · 7 年前

    我想展示一下 decimal 在HTML页面中以美元货币表示的数字。例如,将1209.27显示为 1209美元 二十七 .

    而不是使用 [DataType(DataType.Currency)] 在模型中,我直接在视图中格式化每个数字:

    @Html.Raw(Regex.Replace(Regex.Replace(String.Format("{0:C}", Model.Price), "(?<=\\.)([^.]*$)", "<sup>&nbsp;$1</sup>"), "\\.<sup>", "<sup>"))
    

    有没有一种更有效的方法来实现这种格式而不是重复这一切?

    2 回复  |  直到 7 年前
        1
  •  5
  •   to StackOverflow    7 年前

    您可以考虑编写Razor显示模板或 custom html helper

        2
  •  0
  •   Shawn McGough    7 年前

    根据需要使用CSS设置样式。

    <style type="text/css">
    .price { font-weight: bold;}
    .currency {}
    .decimals { font-size: 0.6em; font-weight: normal; vertical-align: baseline; top: -0.4em; position: relative; }
    </style>
    This item costs 
    <span class="price">
    <span class="currency">$</span>5,310<span class="decimals">.79</span></span> Dollars.
    

    这里的工作小提琴: https://jsfiddle.net/a3vksgcu/1/

    这里的原始解决方案: https://css-tricks.com/forums/topic/solved-a-more-interesting-price-display-using-css/