Hello, I have a very basic problem, but I don't understand why it happens, I have a series of values that I take from ones input
and my goal is to add these values, but the problem is that when I try to add them, I am concatenating instead. Here is my script.
var lun, mart, mier, juev, vier, sab, domin;
lun = $('#lun').val();
mart = $('#mart').val();
mier = $('#mier').val();
juev = $('#juev').val();
vier = $('#vier').val();
sab = $('#sab').val();
domin = $('#domin').val();
$('#ventasError').addClass('hidden');
lun = parseFloat(lun).toFixed(2);
mart = parseFloat(mart).toFixed(2);
mier = parseFloat(mier).toFixed(2);
juev = parseFloat(juev).toFixed(2);
vier = parseFloat(vier).toFixed(2);
sab = parseFloat(sab).toFixed(2);
domin = parseFloat(domin).toFixed(2);
let sumVSem = lun + mart + mier + juev + vier + sab + domin;
debugger //justo sumVSem aquí me tira 1.001.001.001.001.001.001.00 en lugar 7.00
sumVSem = parseFloat(sumVSem).toFixed(2);
$('#promSemanal').val(sumVSem);
Can someone tell me what I'm doing wrong?
Good day
As they told you above, the method
toFixed()
returns a string, if you want to keep it that way, you can modify your code in this way, adding oneparseFloat()
to each variable when doing the sum.I hope it helps you
Although you already have an accepted answer, my answer will focus on optimizing what you're trying to do a bit.
You are repeating the same code 7 times (1 time for each day of the week represented in your elements
<input>
).One way to avoid this repetition would be to list your elements in a type
array
and use its own methods.Suppose your HTML is given like this (all type elements
<input>
are direct children of a parent type element<div>
):You could do the following:
As you can see, I declare a type
array
to store the values of each elementinput
converted to typeNumber
usingparseFloat()
. I then use the methodreduce()
to add up all the values of thearray
and return a single value, which I then apply the methodtoFixed()
to to get the desired result.With this the code is cleaner, and less repetitive.
With that it should work for you.