Reputation: 142
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.
Upvotes: 0
Views: 87
Reputation: 17687
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);">
Upvotes: 2