-2

I am using these in my code:

alert(mult);  //1.114
alert(profit);  //10
price = (mult * profit) + profit;
alert(price);  //11.14 should be 21.14

I also tried price = ((mult*profit) + profit); but got the same result. Instead of doing (1.114*10) + 10; it is doing 1.114*10=11.14. It is not adding the additional 10 at the end.

freginold
  • 3,946
  • 3
  • 13
  • 28
raulxbox
  • 53
  • 1
  • 1
  • 8
  • The `+` operator concatenates its arguments if you give it a string. That means either `mult` or `profit` is a string. Use `parseInt()` and `parseFloat()` to turn a string into a number. – Sidney Sep 06 '17 at 18:36
  • 1
    This isn't concatenation. It's doing the multiplication without adding (or concatenating). If it was concatenating, the result would be `"11.1410"`. Execute this in the console: `'1.114' * '10' + '10'` – ps2goat Sep 06 '17 at 18:38
  • 1
    I'm unable to reproduce. Voting to close the question. @raulxbox please edit your question to include a **Complete, Minimal, and Verifiable example**. – Jared Smith Sep 06 '17 at 18:42
  • 1
    Are you sure it alert `11.14` and not `11.1410`? – Karl-André Gagnon Sep 06 '17 at 18:46

4 Answers4

3

It works fine for me like this. It doesn't seem that concatenation is an issue, because otherwise the value would be '11.1410'.

var mult = 1.114;
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//11.14 should be 21.14

If the profit variable (or both variables) is a string, the result would be "11.1410".

var mult = 1.114;
    var profit = '10';
    var price = (mult*profit) + profit;
    alert(price);//11.1410

The result seems unaffected if just the mult value is a string.

 var mult = '1.114';
        var profit = 10;
        var price = (mult*profit) + profit;
        alert(price);//21.14
ps2goat
  • 8,067
  • 1
  • 35
  • 68
1

The problem is probably that either mult or profit are of type string and not of type number. This can be fixed by explicitly casting.

You can determine the type of your variables in your browser console (i.e. dev tools) with the typeof keyword like this:

typeof foo

If either of your variables are of type string you can convert them to number with parseFloat:

mult = parseFloat(mult);
Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
1

The variables are probably strings, use parseFloat to convert them to numbers :

mult = parseFloat(mult);
profit = parseFloat(profit);
price = (mult*profit) + profit
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

I just ran this is in the chrome js console F12 key.

var mult = 1.114, profit = 10;
console.log('mult=', mult);//1.114
console.log('profit=', profit);//10
price = (mult*profit) + profit;
console.log('price=', price);//11.14 should be 21.14

And got these results

mult= 1.114
profit= 10
price= 21.14
Josh Bowling
  • 313
  • 3
  • 10