Reputation: 23
I have some code that changes the currency on the page from one to another but the problem is it is not showing currency signs and not taking decimal points. check the code below.Does any one know how to use currency sign and currency in decimal like($12.45) in the code below:
var prices = [
1500,
2000,
342
];
var rates = {
USD: 1, // obviously
EUR: 0.86
}
function updatePrices(rate) {
var elements = document.getElementsByClassName("price");
prices.forEach((price, index) => {
elements[index].innerHTML = price * rate
});
}
document.getElementById("selector").onchange = function () {
updatePrices(rates[this.value]);
}
updatePrices(rates.USD);
<div class="row">
<div class="input-field col s1">
<select id="selector">
<option value="USD" selected>USD</option>
<option value="EUR">EUR</option>
</select>
<label>Currency</label>
</div>
</div>
<ul class="currencies">
<li class="price"></li>
<li class="price"></li>
<li class="price"></li>
</ul>
Upvotes: 2
Views: 1549
Reputation: 2242
You can use toFixed to format the result and declare a sing for each
currency (or any other variable you need for example look at something_at_the_end
)
var prices = [
1500,
2000,
342
];
var currencies = {
USD: {
rate: 1,
sign: "$",
something_at_the_end: "test"
},
EUR: {
rate: 0.86,
sign: "€",
something_at_the_end: "EURO TEST"
}
};
function updatePrices(currency) {
var elements = document.getElementsByClassName("price");
prices.forEach((price, index) => {
elements[index].innerHTML = currency.sign + parseFloat(price * currency.rate) + currency.something_at_the_end
});
}
document.getElementById("selector").onchange = function () {
updatePrices(currencies[this.value]);
}
updatePrices(currencies.USD);
<div class="row">
<div class="input-field col s1">
<select id="selector">
<option value="USD" selected>USD</option>
<option value="EUR">EUR</option>
</select>
<label>Currency</label>
</div>
</div>
<ul class="currencies">
<li class="price"></li>
<li class="price"></li>
<li class="price"></li>
</ul>
parseFloat is just to be sure that the result is Number
Upvotes: 1