Knockout / JQuery货币格式

时间:2014-01-15 17:58:18

标签: jquery knockout.js currency-formatting

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

<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>

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

相关问题