I am having numbers that are stringified, such as ["84.0711 billion", "$52.6138 billion", "$43.55 billion", "$54.73 million"]. I would like to convert these numbers back to: ["84071100000", "52613800000", "43550000000", "54730000"]
let numb = ["84.0711 billion", "$52.6138 billion", "$43.55 billion", "$54.73 million"]
const res = []
for (let i = 0; i < numb.length; i++) {
res.push(convertNumber(numb[i]))
}
console.log(JSON.stringify(res));
//wanted output: ["84071100000", "52613800000", "43550000000", "54730000"]
function convertNumber(numb) {
var digits = numb.match(/\d+/g).map(Number);
if (numb.match('billion')) digits + 1000000000
if (numb.match('million')) digits + 1000000
return digits
}
I tried to get only the digits and then add the respective notation. However, I only get the following output.(see above my example)
Any suggestions what I am doing wrong?
You could use a single regex
let numb = ["84.0711 billion", "$52.6138 billion", "$43.55 billion", "$54.73 million"]
const conversion = {
billion: 1000000000,
million: 1000000
};
function convert(entry) {
return entry.replace(/^\$?(\S+)\s?(\w+)/g, (a, n, e) => {
return Number(n) * conversion[e];
})
}
console.log(convert(numb[0]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With