2

I want to format Price and print it in proper format. For example, 5000000 will be displayed as $5,000,000. Can anyone tell me how it can be done?

<span data-bind="text:Price"></span>

<span data-bind="function()"></span>

Can I write an inline function which will take the value and format it? Can the value of text: Price be passed to formatfunction()?

formatfunction(label){return  '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Swap
  • 189
  • 1
  • 1
  • 13
  • This GIST might be helpful: https://gist.github.com/jakiestfu/7894971 – David Tansey Mar 08 '16 at 19:02
  • Or this SO post: http://stackoverflow.com/questions/21144883/knockout-jquery-currency-format – David Tansey Mar 08 '16 at 19:03
  • And another good one: https://theweeklybyte.wordpress.com/2014/04/19/three-useful-knockoutjs-extenders/ – David Tansey Mar 08 '16 at 19:04
  • Check this: http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – Cristian Michel Mar 08 '16 at 19:06
  • @DavidTansey I tried the code but it isn't working. Can you tell me where should I add the javascript function mentioned in the link? Refer http://stackoverflow.com/questions/21144883/knockout-jquery-currency-format – Swap Mar 08 '16 at 19:47
  • That's post is showing a loose JS function. You should be able to add that function block to any other JS code you already have, as long as you paste it into the appropriate place. – David Tansey Mar 08 '16 at 20:39

4 Answers4

2

One clever thing about Knockout is that bindings are snippets of code, so you can use expressions in them. So you can call a function:

<span data-bind="text:formatfunction(Price)"></span>

Just, as a rule, try not to let the expressions get very complicated. Complicated expressions belong in your viewmodel.

Roy J
  • 42,522
  • 10
  • 78
  • 102
0

You can use knockout computed variables for that, see examples from knockout.

jmvtrinidad
  • 3,347
  • 3
  • 22
  • 42
0

You can use sample below.

(function() {
    function refresh(element, valueAccessor) {
        var val = ko.utils.unwrapObservable(valueAccessor());
        var text =  '$' + val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        $(element).text(text);
    }

    ko.bindingHandlers.priceText = {
        init: refresh,
        update: refresh
    }
})();
<span data-bind="priceText:Price"></span>

This will keep you model clean from UI specific "formatting" computeds and thus will make it more reusable. Plus you can add price observable(s) to any model you want without adding a computed every time.

0

function ViewModel() {

var self=this;
self.formatfunction=function(label){
                    console.log(label);
                    return  '$' + label.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

ko.applyBindings(new ViewModel());
<span data-bind="text:$parent.formatfunction(Price)"></span>
Swap
  • 189
  • 1
  • 1
  • 13