Number string to number without knowing the format used in Javascript

Viewed 32

Is there a generic way or regex that handles all possible number formats in string and converts to correct number. For example:

"1.234,21" to 1234.21
"1,234.21" to 1234.21
"1234,21" to 1234.21
"1234.21" to 1234.21
"1,234,567.21" to 1234567.21
"1.234.567,21" to 1234567.21

Edit: Should also handle

"1,234,567" to 1234567
"1.234.567" to 1234567
1 Answers

Solution

A little bit hacky, but works:

const strings = [
"1.234,21",
"1,234.21",
"1234,21",
"1234.21",
"1,234,567.21",
"1.234.567,21",
'1234'
]

const numbers = strings.map(str => {
  const [, int, frac] = str.match(/^(\d+(?:[,.]\d+)*?)+?(?:[,.](\d+))?$/)
  return Number(int.replace(/[,.]/g, '')) + (frac ? Number('0.' + frac) : 0)
})

console.log(numbers)

Explanation

This regex splits the string into two parts by the last , or .

/^(\d+(?:[,.]\d+)*?)+?(?:[,.](\d+))?$/

This converts the integer part to a number:

Number(int.replace(/[,.]/g, ''))

This converts fraction part into a number (if it exists):

frac ? Number('0.' + frac) : 0
Related