I want to make a simple calculator. My problem is in the addition function, when I enter the value it does not add the two value but instead concatenate those two value. Can someone help me fix this. Here are my coding:
var Calculator = function (number,addNum) {
var self = this;
self.number = ko.observable(number);
self.addNum = ko.observable (addNum);
self.sum = ko.computed(function(){
return self.number() + self.addNum();
});
}
ko.applyBindings(new Calculator());
1 Answer
Because they're bound to input boxes, self.number() and self.addNum() are strings (even if they are originally numbers). Use parseFloat()...
self.sum = ko.computed(function(){
return parseFloat(self.number()) + parseFloat(self.addNum());
});