inspiringmyself
inspiringmyself

Reputation: 590

Knockout - is toFixed the right function to shift decimal points in a number

I am trying to create a computed observable from an observable. In this scenario, the observable is the precision and I want a value to be fixed to that observable value.

this.precision = ko.observable("2");

this.formattedValue = ko.computed(function(){
      return "567".toFixed(this.precision());
});

I am not able to make this work. It complains "undefined is not a function".

Any suggestions?

Upvotes: 0

Views: 3530

Answers (1)

Wayne Ellery
Wayne Ellery

Reputation: 7958

toFixed works on a number and not a string and the precision is also a number. (567).toFixed(2) will return 567.00.

You need to use self instead of this because inside a function this will refer to itself.

var ViewModel = function () {
    var self = this;
    self.precision = ko.observable(2);

    self.formattedValue = ko.computed(function(){
        return (567).toFixed(self.precision());
    });
};

http://jsfiddle.net/64SC8/1/

To shift the decimal point to the left so 567 becomes 5.67 you can use 565 / Math.pow(10, self.precision())

http://jsfiddle.net/64SC8/2/

Upvotes: 2

Related Questions