Working with currency in Javascript

currency_vs_javascript

These days I was developing in VB.NET. This application was working basically as a web service, and through the Javascript I made my asynchronous requests.

Everything was working fine, but I was working with currency. If you’ve already worked with currency, probably you should have had some problem. Especially if your backend project is set to a different culture type.

I am Brazilian, usually the projects that I work are configured as pt-BR. The response that I got from the web service was a currency setted to pt-BR. Examples: R$ 10,00 / R$ 1.000,00

Of course, I could just change the culture type of the web service return, it would make my life easier, but I hadn’t this option. I had to do everything in Javascript and I didn’t want to import a currency library.

Come aboard!

Currency to float

The first thing I needed to do is to create a function that would transform currency in a float.

function real2float(moeda) {
    moeda = String(moeda);
    moeda = moeda.replace("R$", "");
    moeda = moeda.replace(/\./g, ""); // it replaces all dots
    moeda = moeda.replace(",", ".");
    return parseFloat(moeda);
}
real2float("R$ 1.000,00") // 1000
real2float("R$ 974.430,30") // 974430.30
real2float("R$ 1.966.854,88") // 1966854.88

Now I could work with these numbers and make calculations. After that, I needed to transform these numbers in currency again to display them on screen.

Float to currency

To transform float to currency, I used the method toLocaleString.

“The toLocaleString() method returns a string with a language sensitive representation of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.”

function float2real(valor) {
    valor = parseFloat(valor).toFixed(2).toString();
    valor = parseFloat(valor).toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
        minimumFractionDigits: 2
    });
    valor = valor.replace("R$", "R$ ");
    return valor;
}
float2real(100.00) // R$ 100,00
float2real(500.29) // R$ 500,29
float2real(504440.93) // R$ 504.440,93

Conclusion

If you do work with a several types of currency in Javascript, could be a good idea to use some library. GitHub exists to help you to find good libraries and frameworks.
Or if you work with just one type of currency, I would recommend you to create manually 2 simple functions, like I did.
To know more about the toLocaleString method, take a look at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString