2014-01-15 75 views
0

我有下面的页面工作得很好(我已经删除了一些其他字段和样式,以保持我在这里发布的样本不多)。我希望表中的Premium行(第17行)格式化为货币(USD)。这样做的最好方法是什么?Knockout/JQuery货币格式

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 
    <div class="datagrid" > 
     <table > 
      <thead> 
       <tr> 
        <th>Location Name</th> 
        <th>Location Total</th> 
       </tr> 
      </thead> 
      <tbody data-bind="foreach: { data: Locations, as: 'location' }"> 
       <tr> 
        <td><span data-bind="text: location.LocationName" /> </td> 
        <td><span data-bind="text: location.Premium" /> </td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 

    <script> 
     $(document).ready(function() 
     { 
      var appViewModel 

      // AppViewModel 
      function AppViewModel() 
      { 
       this.Locations = ko.observable([]); 
      } 
      var appViewModel = new AppViewModel(); 

      ko.applyBindings(appViewModel); 

      $.getJSON("http://waltweb01:85/LTCEPLWS/LTCJSON.svc/getLTCWithIDs/4", function (data) 
      { 
       incomingData = data; 
       appViewModel.Locations(data.getLTCWithIDsResult.Locations); 
      }); 
     }); 
    </script> 
</asp:Content> 
+0

复制http://stackoverflow.com/questions/5807155/jquery-currency-格式编号 – Charles380

+0

不重复。坦率地说,我看不出连接的被指控程序的13票答案如何适用于该页面的原始问题。 –

+0

无论如何...我已经使用“

回答

0

淘汰赛有这些东西叫extenders,我认为这些情况下是有用的。这个例子是四舍五入的,但很容易设置它来添加美元符号或转换货币。通过这种方式,您还可以在网站的其他区域使用扩展程序,该扩展程序也需要转换/格式化为美元。

3

答案已隐藏在评论中,以便将来读者更容易找到答案。

更改您的HTML代码:

<td><span data-bind="text: formatCurrency(location.Premium())" /> </td> 

,然后添加的JavaScript formatCurrency()函数:

var formatCurrency = function (amount) { 
    if (!amount) { 
     return ""; 
    } 
    amount += ''; 
    x = amount.split('.'); 
    x1 = x[0]; 
    x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
     x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    return "$" + x1 + x2; 
}