Knockout / JQuery货币格式

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

 
Location Name Location Total
$(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); }); });

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

将您的HTML代码更改为:

   

然后添加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; } 

Knockout将这些称为扩展器的东西我认为在这些情况下很有用。 该示例用于舍入,但很容易将其设置为添加美元符号或转换货币。 通过这种方式,您还可以在站点的其他区域使用扩展器,这些区域也需要转换/格式化为美元。