Include the plugin
You must first include the plugin and particularly the bigmoney-all.js
:
<script src="bigmoney-all.js"></script>
If you are working with Node JS, you can do this at the cost of require('bigmoney')
, as long as you first place it in the node_modules folder.
Configuring conversions
Then you can set the various currencies available as well as your conversion rates if you want to be able to convert between currencies:
Money.settings = {
base: "BRL",
rates: {
BRL : 1, //Esta é a base, as outras são calculadas convertendo a partir desta
USD: 0.31,
EUR: 0.25
},
format: "%decimal %currency"
}
With special attention that the conversions that I put refer the day this answer was published.
Conversions are made by calling the convert
method passing the currency you want to convert to:
dinheiro.convert('USD'); //obter o resultado da conversão para dólar americano
Create money
Now each time you want to work with the currency, just create a new object with Money()
and specify the currency:
let dinheiro = Money(325, "BRL");
Available operations
If you want to operate on this money you can use the various arithmetic operators available from the library:
-
plus
- add
-
minus
- subtract
-
times
- multiply
-
div
- divide
-
mod
- rest of the division
Remembering that each operation returns the new result.
Now let's look at an example where we calculated and added 10% of $ 325:
let dinheiro = Money(325, "BRL");
dinheiro = dinheiro.plus(dinheiro.div(10)); //dinheiro soma com dinheiro a dividir por 10
console.log(dinheiro.valueOf()) //357.5
At any time you want to know the value that the variable has just use the method valueOf
.
Formatting
To show specifying a format you must use the format
method:
console.log(dinheiro.format("R$ %decimal")); //mostra R$ 357.5
You can even set the currency format to simplify later formatting at the expense of formatter
:
Money.formatter = function(decimal, currency, formatParam) {
switch(currency) {
case 'USD': return "$" + decimal;
case 'EUR': return "€" + decimal;
case 'JPY': return "¥" + decimal;
case 'BRL': return "R$ " + decimal;
default: return decimal + " " + currency;
}
};
Now if you have money in the real format, just show calling format
with no parameters:
let dinheiro = Money(100, "BRL");
console.log(dinheiro.format()); //mostra R$ 100
You can even use the formatting available at Number.toLocaleString to simplify and stay closer to the one you use day by day:
Money.formatter = function(decimal, currency, formatParam) {
switch(currency) {
case 'USD': return "$" + decimal;
case 'EUR': return "€" + decimal;
case 'JPY': return "¥" + decimal;
case 'BRL': return decimal.toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});
default: return decimal + " " + currency;
}
};
let dinheiro = Money(100, "BRL");
console.log(dinheiro.format()); //mostra R$100,00