如何在javascript中编写货币转换器?

时间:2012-06-19 07:31:01

标签: javascript

如何搜索包含欧元或欧元或其他货币的文本中的所有部分,以将其转换为我选择的其他货币?

即:

  1. 如何隔离€或EUR或其他货币符号的左侧或右侧数字?
  2. 如何使用更改后的值替换该数字?
  3. 如何将这个应用于之前或之后有欧元或欧元或其他货币符号的所有网页?

2 个答案:

答案 0 :(得分:1)

以下是一些示例代码,用于搜索任何货币的文本并转换为目标货币:

var currencies = {
    "EUR": ["€", "EUR", "EURO", "EUROS"],
    "USD": ["$", "USD", "USDOLLAR", "USDOLLARS"],
    "DEM": ["DEM", "DM", "Deutsche Mark"]
};
var rates = {
    "EUR": { USD: 1.2613, DEM: 1.96 },
    "USD": { EUR: 0.792832792, DEM: 1.54315 },
    "DEM": { USD: 0.648121, EUR: 0.51 }
};
function currencyReplacer(number, sourceCurrency, targetCurrency, currencyFormatIndex, currencySeparator) {
    var c, i, comma = /,/g;
    for (c in currencies) {
        if (currencies.hasOwnProperty(c)) {
            for (i = 0; i < currencies[c].length; i++) {
                if (currencies[c][i] === sourceCurrency) {
                    console.log(rates[c][targetCurrency], number);
                    return [Math.round(rates[c][targetCurrency] * number.replace(comma, "."), 2), currencies[targetCurrency][currencyFormatIndex || 0]].join(currencySeparator || "");
                }
            }
        }
    }
    return m;
}
function replaceCurrencies(text, sourceCurrency, targetCurrency, currencyFormatIndex, currencySeparator) {
    var prefixedRegex = new RegExp("(" + currencies[sourceCurrency].join("|") + ")\\s?(\\d+(?:(?:,|.)\\d+)?)", "gi");
    var suffixedRegex = new RegExp("(\\d+(?:(?:,|.)\\d+)?)\\s?(" + currencies[sourceCurrency].join("|") + ")", "gi");
    return text.replace(prefixedRegex, function(m, currency, number) {
        return currencyReplacer(number, currency, targetCurrency, currencyFormatIndex, currencySeparator);
    }).replace(suffixedRegex, function(m, number, currency) {
        return currencyReplacer(number, currency, targetCurrency, currencyFormatIndex, currencySeparator);
    });
}
replaceCurrencies("This function will convert currencies: €50 is less than 100 EUR which is more than 75 €", "EUR", "DEM", 1, " ");
// will output: "This function will convert currencies: 98 DM is less than 196 DM which is more than 147 DM"

这可以解决你的问题吗?

编辑:更新了上面的代码以包含您想要的目标货币DEM,并使正则表达式/替换程序支持前缀和后缀以及sourceCurrency

Edit2:再次更新代码以处理小数

答案 1 :(得分:0)

如果真的使用了货币,就无法在文本中找到。

例如,您如何区分这些:

  • €币很好
  • 我们需要50欧元(欧元)
  • 不同于50€
  • 同样为$
  • 可以像这样使用50美元
  • 或者喜欢这个50美元
  • 或者甚至喜欢这个50美元(欧洲人)

但我会让你处理这部分。

如果你有你知道的字符串它是一种货币,你可以这样玩:

// Find out what's the currency used
if ( /[$]/.test( str ) ) // Currency is $
else if ( /[€]/.test( str ) ) // Currency is €

// etc. To get the number out of this string, use:
var val = /\d+/.exec( str ); // if "str === 50$", it returns "50"