Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert stringified numbers back to number

Tags:

javascript

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?

like image 786
Carol.Kar Avatar asked Jan 30 '26 06:01

Carol.Kar


1 Answers

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]));
like image 80
baao Avatar answered Feb 01 '26 22:02

baao