Simple Calculator Knockout

Simple Calculator Knockout

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

Live Demo

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.