DEV Community

Cover image for Formatação de moedas em JavaScript
Francisco Chaves
Francisco Chaves

Posted on • Updated on • Originally published at franciscochaves.com.br

Formatação de moedas em JavaScript

Olá pessoal, hoje irei deixar uma dica bem legal para formatar algum valor numérico para a moeda Real, Dólar e Euro.

const currentValue = 1265.8;

const valueBR = currentValue.toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});
console.log(valueBR); // R$ 1.265,80

const valueUSD = currentValue.toLocaleString('pt-BR', {style: 'currency', currency: 'USD'});
console.log(valueUSD); // US$ 1.265,80

const valueEUR = currentValue.toLocaleString('pt-BR', {style: 'currency', currency: 'EUR'});
console.log(valueEUR); // € 1.265,80
Enter fullscreen mode Exit fullscreen mode

Caso deseje realizar a operação inversa, utilize o código abaixo:

const valueBR = 'R$ 1.265,80';

const currentValue = Number(valueBR.replace(/\D/g, '')) / 100;
console.log(currentValue); // 1265.8
Enter fullscreen mode Exit fullscreen mode

Valeu pessoal 😎✌!

Top comments (0)