我想知道如何输出用户想要在我的货币转换器中转换金额的不同货币符号?例如,如果我想在新金额的最终产出(即20欧元的欧元价值)中将20英镑兑换成欧元,我怎样才能输出欧元符号?最终输出只是数字,我想要在最终价值金额输出前面的货币符号,我想知道如何为输出金额的每种货币执行此操作。我正在从API导入实时汇率,我如何导入汇率但是添加货币符号?
JAVASCRIPT
// Fetch exchange rate data from api
$.getJSON("https://api.fixer.io/latest?base=ZAR", function(data) {
var currencies = [];
$.each(data.rates, function(currency, rate) {
// Currency options dropdown menu
currencies.push("<option id='" + currency.toLowerCase() + "' value='" + rate + "' >" + currency + "</option>");
});
$(".currency-list").append(currencies);
})
//Calculate and output the new amount
function exchangeCurrency() {
var amount = $(".amount").val();
var rateFrom = $(".currency-list")[0].value;
var rateTo = $(".currency-list")[1].value;
if (amount == undefined || rateFrom == "--Select--" || rateTo == "--Select--") {
$(".results").html("0");
} else {
$(".results").html((amount * (rateTo * (1 / rateFrom))).toFixed(2));
}
}
答案 0 :(得分:2)
您可以使用Localestring
var number = 123456.789;
// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })); // → 123.456,79 €
var currency = document.getElementById('currency');
var Euro = number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
currency.innerHTML = Euro;
&#13;
<p id='currency'></p>
&#13;
这是我的jsfiddle:
答案 1 :(得分:0)
虽然您可以使用支持Intl对象的 toLocaleString ,但您也可以使用小型查找表(例如{euro:'€',pound:'£', ...}
)作为符号,并format as money手动使用
/*
https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript/149099#149099
decimal_sep: character used as deciaml separtor, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{
var n = this,
c = isNaN(decimals) ? 2 : Math.abs(decimals),
d = decimal_sep || '.',
t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
sign = (n < 0) ? '-' : '',
i = parseInt(n = Math.abs(n).toFixed(c)) + '',
j = ((j = i.length) > 3) ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}
var currencySymbol = {euro:'€',pound:'£',dollar:'$'};
var amount = 123546.23
document.getElementById('moneyAmount0').innerHTML = currencySymbol.euro + amount.toMoney();
document.getElementById('moneyAmount1').innerHTML = currencySymbol.euro + amount.toMoney(2,',','.');
<p>Amount (English): <span id="moneyAmount0"></span></p>
<p>Amount (European): <span id="moneyAmount1"></span></p>
请注意, toLocaleString 的结果仍然主要依赖于实现,如果没有对选项的支持,您不知道它会回退到什么程度。
.toMoney 功能来自How can I format numbers as money in JavaScript?的最高评分答案
答案 2 :(得分:0)
您是否有办法获得货币名称(即&#34;欧元&#34;,&#34;美元&#34;,&#34;磅&#34;等)?如果是这样,请执行以下操作:
currencySymbols = {euros:'€',dollars:'$',pounds:'£'};
finalText = currencySymbols[currencyText.toLowerCase()] + currencyValue;
这会为您提供类似$42
或£6.38
的内容。