Skip to content

Instantly share code, notes, and snippets.

@diegomais
Created January 31, 2021 20:43
Show Gist options
  • Save diegomais/38893fbacdbbd9768badfa5a86eeeef0 to your computer and use it in GitHub Desktop.
Save diegomais/38893fbacdbbd9768badfa5a86eeeef0 to your computer and use it in GitHub Desktop.
Reverse the formatting by Intl.NumberFormat in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Intl.NumberFormat</title>
<script type="text/javascript" charset="UTF-8" src="script.js"></script>
</head>
<body>
<output id=output></output>
</body>
</html>
const exp = /^\w{0,3}\W?\s?(\d+)[.,](\d+)?,?(\d+)?$/g
const replacer = (f, group1, group2, group3) => {
return group3 ? `${group1}${group2}.${group3}` : `${group1}.${group2}` }
const usd = '$10.15'.replace(exp, replacer)
// 10.15
const eu = '€01.25'.replace(exp, replacer)
// 1.25
const brl = 'R$ 14.000,32'.replace(exp, replacer)
// 14000.32
const tai = 'TAI 50.230,32'.replace(exp, replacer)
// 50230.32
// just to test!
const el = document.getElementById('output')
const reverseUSD = new Intl.NumberFormat('en-us', { style: 'currency', currency: 'USD' }).format(usd)
el.innerHTML += `<br> from: ${reverseUSD} to ${parseFloat(usd)}`
const reverseBRL = new Intl.NumberFormat('pt-br', { style: 'currency', currency: 'BRL' }).format(brl)
el.innerHTML += `<br> from: ${reverseBRL} to ${parseFloat(brl)}`
const reverseTAI = new Intl.NumberFormat('en-us', { style: 'currency', currency: 'TAI' }).format(tai)
el.innerHTML += `<br> from: ${reverseTAI} to ${parseFloat(tai)}`
const reverseEU = new Intl.NumberFormat('eur', { style: 'currency', currency: 'EUR' }).format(eu)
el.innerHTML += `<br> from: ${reverseEU} to ${parseFloat(eu)}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment