I have a set of strings in my dom with the same class. I need to convert the strings to numbers and then perform a cacluation on them and return them to the screen. I have used parseInt, parseFloat, Number() and even coercion using +variable; without any converson. I show typeof as "string" in every case. I am unsure what I am doing wrong. Can someone please help me find what I am missing? Here s my html:
<div class="price">
<span class="label">from</span>
<span class="value">
<span class="text-lg lh1em item "> $3,845.00</span>
</span>
<span class="value">
<span class="text-lg lh1em item "> $3,645.00</span>
</span>
</div>
and my Javascript is as follows:
let customPrice = document.getElementsByClassName('lh1em');
Array.from(customPrice).forEach(function(dollarAmount) {
let withoutDollar = dollarAmount.innerText.substr(1);
let withoutComa = withoutDollar.replace(",",'');
// parseFloat(withoutComa);
let noPointZero = withoutComa.replace(/\.00/, '');
// noPointZero * 1;
// parseInt(noPointZero);
Number(noPointZero);
console.log(typeof noPointZero);
});
Without the typeof, I get the correct number value as a string. How can I force this to be a number? Thank you.
You have a space at the beginning of the text. So substr(1)
is removing the space, not the $
. Use trim()
to remove surrounding whitespace.
You also need to assign the result of Number()
at the end. It's just like all your other fixups -- it returns a new value, it doesn't modify the value in place.
To replace commas you need to use a regular expression with the g
modifier. Replacing a string only replaces the first occurrence.
Array.from(customPrice).forEach(function(dollarAmount) {
let withoutDollar = dollarAmount.innerText.trim().replace(/^\$/, '');
let withoutComa = withoutDollar.replace(/,/g,'');
// parseFloat(withoutComa);
let noPointZero = withoutComa.replace(/\.00$/, '');
// noPointZero * 1;
// parseInt(noPointZero);
let numeric = Number(noPointZero);
console.log(typeof numeric);
});