1

happy new year!

Here is my code:

var totalwin,pradinisStatymas

function Increase()
{
    ....
    ....
    totalwin += pradinisStatymas; //I'm adding increasing totalwin by pradinisStatymas
    return print();
}


function print()
{
    locale[lang][7] = "Total win: ";
    var a="<br>"+locale[lang][7]+totalwin+"<br>";
    bot_debug(a,0);
}

$bCons = $("#botConsole");
function bot_debug(text,type)
{
    switch(type)
    {
        case 0:{$bCons.css("color","#353535"); $bCons.html(text); break;}
        case 1:{$bCons.css("color","#C12E2A"); $bCons.html(text); break;}
        case 2:{$bCons.css("color","#419641"); $bCons.html(text); break;}
    }
}

The problem is, if I set "pradinisStatymas" to 5, it should change $bCons's text to "Total win: 5", but instead it changes text to "Total win: 05".

If I increase it even further, it will keep adding the pradinisStatymas value at the end "Total win: 055".

It was working fine when I was using javascript console instead of html text. I think I need to do some formatting, but I'm not sure how. Thanks for help.

Ned
  • 361
  • 3
  • 16
  • 4
    Looks like you're mixing _String_ and _Number_, causing the `+` operator to do _string concatenation_ instead of _addition_ – Paul S. Jan 01 '16 at 13:27

1 Answers1

1

You've left out the important bit, which is how/where you're getting pradinisStatymas, but the symptom makes the problem fairly clear: The value in pradinisStatymas is a string. (Perhaps you're getting it from an input element's value.) So += is string concatenation, not addition.

If we assume that totalwin is set to 0 initially (and thus is a number to start with), convert pradinisStatymas to a number before the +=, e.g.:

totalwin += +pradinisStatymas;
// or
totalwin += Number(pradinisStatymas);
// or (if it's meant to be an integer)
totalwin += parseInt(pradinisStatymas, 10);
// or
totalwin += parseFloat(pradinisStatymas);

Those are some of your options, the third one one assumes that is meant to be an integer (whole number). My answer here goes into detail of the various options.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • As we don't know how `totalwin` is set either, it may be wise to do `foo = +foo + +bar` instead of `foo += +bar` – Paul S. Jan 01 '16 at 13:29
  • In your first case, `+pradinisStatymas`, does the `+` convert a string to a number? I'd like to read up more on that. – christofr Jan 01 '16 at 13:31
  • 1
    @christofr: Yes, `+n` does exactly what `Number(n)` does, but without the function call and the possibility of someone shadowing the `Number` symbol (unlikely, but...). – T.J. Crowder Jan 01 '16 at 13:34
  • 1
    Thanks a lot for the help @T.J.Crowder! – Ned Jan 01 '16 at 13:46