将 html 页面中的所有价格从一种货币更改为另一种货币?

问题描述

我有一些代码可以将页面上的货币从一种更改为另一种,但问题是它不显示货币符号并且不带小数点。检查下面的代码。有谁知道如何在下面的代码中使用货币符号和十进制货币,例如($12.45):

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>

解决方法

您可以使用 toFixed 来格式化结果并为每个 货币(或您需要的任何其他变量,例如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 只是为了确保结果是 Number

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...