Nedas Mikoleika Nedas Mikoleika - 4 years ago 113
HTML Question

Wrong variable data

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download