Add 4 numbers together

I am trying to add 4 numbers together, but instead of give it like this (0.00049358 + 0.13645312 + 0.1000 + .2000 = 0.4369467) but it gives me this result ( 0.000493580.136453120.10000.2000) when i press button, what is wrong with my code

function add1(){
    var num20= document.getElementById("result1").value;
    var num21= document.getElementById("result3").value;
    var num22= document.getElementById("result6").value;
    var num23= document.getElementById("result8").value
    var result9 = num20 + num21 + num22 + num23;
    document.getElementById("result9").value = result9.toLocaleString('en-US',{ maximumFractionDigits: 8 });

When you get them from the DOM, those values are passed as string, so as for JS is concerned you are concatenating strings, rather than sum up numbers.

You probably want to convert the values into floats.

Hope this helps.

Thank you, I am new to JavaScript, now you talk about floats, something new to try and learn about

Not really javascript, but math in general.
Those numbers are not integers, but floating points.

Be aware of floating point imprecision which is a thing in computer science/math

0.1 + 0.2 = 0.30000000000000004

Good luck and happy coding :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.