-1

well I'm trying to make a calculator in google scripts and whenever I try to add it concentrates rather than adding I've searched for hours any help would be greatly appreciated I have checked several forum posts and none answers my question as they have their variable already in an integer

function calculateNumber() {
     var calc = DocumentApp.getUi()
     var num1 = calc.prompt('Please Type First Number', calc.ButtonSet.OK)
     var one = num1.getResponseText();
     var num2 = calc.prompt('Please Type Operator', calc.ButtonSet.OK)  
     var two = num2.getResponseText()
     var num3 = calc.prompt('Please Type Second Number', calc.ButtonSet.OK)
     var three = num3.getResponseText()
     var n1 = eval(one)
     var n2 = eval(two)
     var sum = n1+n2
     if (two == '+') {
       calc.alert('Ans='+sum)

     }
   }
JackThePug
  • 3
  • 1
  • 1
  • 4
  • 1
    Perhaps try changing `var sum = n1+n2` to `var sum = parseInt(n1) + parseInt(n2)` – Nick Jan 17 '19 at 23:50
  • Why do you use eval ? [eval is evil](https://coderwall.com/p/mkicig/eval-is-evil) – Beniamin H Jan 18 '19 at 00:13
  • @Nick Better to use `Number`, I think – CertainPerformance Jan 18 '19 at 00:16
  • @CertainPerformance ah, why is that? – Nick Jan 18 '19 at 00:17
  • 1
    @Nick `parseInt` also accepts a radix argument, which can often cause confusion - also, `parseInt` will only transform the input to an *integer*, not just to a number (like to `0.2`) - if all you want to do is coerce, probably best to just use `Number` – CertainPerformance Jan 18 '19 at 00:18
  • Add more details like a sample input values and the expected results.(maybe you are using comma as decimal separator ) – Rubén Jan 18 '19 at 00:20
  • @CertainPerformance oh alright, awesome. Thanks. I think since early on the radix argument has been a non factor. I remember at some point it was base 2 or something. But yeah the decimal piece is certainly a great reason. – Nick Jan 18 '19 at 00:22

2 Answers2

0

n1 and n2 are strings, you need to cast them to integers, use parseInt(n1) + parseInt(n2);

Beniamin H
  • 2,048
  • 1
  • 11
  • 17
Andy Upton
  • 11
  • 2
0

Try something like this:

function calculateNumber() {
     var calc = DocumentApp.getUi()
     var num1 = calc.prompt('Please Type First Number', calc.ButtonSet.OK)
     var one = num1.getResponseText();
     var num2 = calc.prompt('Please Type Operator', calc.ButtonSet.OK)  
     var two = num2.getResponseText()
     var num3 = calc.prompt('Please Type Second Number', calc.ButtonSet.OK)
     var three = num3.getResponseText()
     if (two === '+') {
       var sum = Number(one)+Number(three);
       calc.alert('Ans='+sum)

     }
   }
Mo A
  • 717
  • 1
  • 8
  • 19