Talon Blackthorne
Talon Blackthorne

Reputation: 27

Knockout/JQuery currency format

I have the below page working pretty well (I've cut out some other fields and styling to keep the sample that I post here smallish). I'd like the Premium line in the table (line 17) to format as currency (USD). What's the best way of doing this?

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

Upvotes: 0

Views: 7159

Answers (2)

Rocklan
Rocklan

Reputation: 8130

Answer is hidden in the comments so to make it easier for future readers here's an answer.

Change your HTML code to:

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

And then add the javascript formatCurrency() function:

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

Upvotes: 3

maggiekh
maggiekh

Reputation: 204

Knockout has these things called extenders which I think are useful in these cases. The example is for rounding, but it's easy enough to set it up to add a dollar sign or convert the currency. In this way you can also use the extender in other areas of your site which also need conversion/formatted to dollars.

Upvotes: 0

Related Questions