0

I'm not sure what's wrong.

There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.

Thanks for any help!

function priplatok(vstup1, vstup2) {
    var chid = vstup1;
    var cena = vstup2;
    var uhrada = document.getElementById('uhr').value;

    if (document.getElementById(chid).checked) {
        var pridatu = uhrada + cena;   
        alert(pridatu); 
    }
}
noahnu
  • 3,479
  • 2
  • 18
  • 40
Daniel
  • 19
  • 5

3 Answers3

4

The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():

var pridatu = parseFloat(uhrada) + parseFloat(cena);

A shorter way is to force conversion with a +:

var pridatu = +uhrada + +cena;

Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286
3

You get a string from document.getElementById('uhr').value.

If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.

Your code:

function priplatok(vstup1, vstup2) {
    var chid = vstup1;
    var cena = vstup2;
    var uhrada = +document.getElementById('uhr').value; // use implicit cast to number

    if (document.getElementById(chid).checked) {
        var pridatu = uhrada + cena;
        alert(pridatu);
    }
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:

var pridatu = parseInt(uhrada) + parseInt(cena);
John
  • 760
  • 5
  • 12