0

I have a value separated by commas. The code is as follows:

function addComma(values) {
  const v = values.value && new Number(values.value.replace(/,/g, ''));
  values.value = v.toLocaleString();
}

if (document.getElementById("values"))
  var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">

Issue:

if (selectedPayType === "A") {
                PV = getNPV(rate, array, payment) + payment;
                console.log("PV);
            }

For some reason, PV returns the value but it doesn't add the +payment. But, instead of +payment, if i use the numeric value itself ex: 10000, then it adds the value up.

I tried debugging and it is taking the payment value inside the getNPV however, not adding it up which is really weird. Not sure what i am doing wrong here. Any help is appreciated. Thank you.

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
ace23
  • 142
  • 1
  • 16

1 Answers1

2

The main problem is that you are adding a string to a number . For eg: 1 + '2' = '12'. So you need to convert your payment which is a string, into a number.

Do not use Number constructor as it might cause unwanted results, but use parseFloat or parseInt to convert numeral strings into numbers.

p.s. for parseInt you should/need to specify a radix .

Useful links

Changed a bit the structure ( added the if inside the addComma function that is called onkeyup )

See below

function addComma(values) {
  const v = values.value && parseFloat(values.value.replace(/,/g, ''));
  values.value = v.toLocaleString();


   if (document.getElementById("values")) {
    var pay = document.getElementById("values").value;
    payment = pay.replace(/\,/g, '');
    PV = 10 + parseFloat(payment);
    console.log(PV);
   }
}
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">
Mihai T
  • 17,254
  • 2
  • 23
  • 32
  • Glad i could help. I also shared a few useful links for you. I advise you to read them. Thanks for the upvote. Cheers ! :D – Mihai T Dec 03 '18 at 15:48