Home > Software engineering >  Javascript - How to extract float number from a string for calculation using regex
Javascript - How to extract float number from a string for calculation using regex

Time:11-27

I have this code in one vue method and I want to optimize it. I will get some information from a WP database and these informations contains also some text that I don't need.

I don't like the regex I've used, since I will need to create the data using template literal. The information passed to the method with the prodInfo variable looks like this 2,5kg meal or 500g cookie

Is there a better way to do the calculations and to get the needed information?

extractTotal(prodInfo, prodPrice, code){
  let val = prodInfo.match(/[0-9]/g)
  let multiplier
  if( val.length > 2 ){
    multiplier = `${val[0]}${val[1]}${val[2]}`
  } else if( val.length === 1 ) {
    multiplier = val[0]
  } else {
    multipier = `${val[0]}.${val[1]}`
  }

  if( multiplier === '500' ){
    return (parseFloat(prodPrice) * this.q[code] / 2)
  } else if( multiplier === '1' ) {
    return (parseFloat(prodPrice) * this.q[code] * 1)
  } else {
    return (parseFloat(prodPrice) * this.q[code] * multiplier)
  }

}

CodePudding user response:

Use this regex: /[0-9] \,?[0-9]*/g

Then you can convert the , chars to .

// Example
const input = '2,5kg meal 500g cookie'
const floats = input
  .match(/[0-9] \,?[0-9]*/g)
  .map(a => parseFloat(
    a.replace(',','.')
  )
)

// floats => [2.5, 500]
  • Related