Reputation: 590
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
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());
});
};
To shift the decimal point to the left so 567 becomes 5.67 you can use 565 / Math.pow(10, self.precision())
Upvotes: 2