价格字符串分为金额和货币

时间:2017-07-25 17:36:02

标签: javascript typescript

我需要帮助在javascript中拆分字符串。

我有一个带货币的字符串。字符串取决于位置。

例如:" 1,99€"或" $ 1,99"

我想拆分字符串并提取"金额"和货币"出来的。

如果失败,我想返回一个空字符串或只是null。

有人知道如何解决这个问题吗?

5 个答案:

答案 0 :(得分:1)

如果您希望所有输入都包含分值的小数(即,您的逗号将始终跟随2位数字),您可以使用此:

const amount = money.match(/\d/g).join('') / 100;
const curren = money.match(/[^\d,]/g).join('');

JavaScripts非常讨厌隐式类型强制允许我们将该字符串分子除以数字分母,最后得到一个数字。

要获取货币,我们只需提取所有非数字或逗号字符并加入它们。

如果您不能依赖包含分值的输入(即,您可能会收到一个没有逗号或分数位的全部金额),请尝试:

const amount = money.match(/d/g).join('') / (money.includes(',') ? 100 : 1);

答案 1 :(得分:1)

尝试这种方式从字符串中获取amountcurrency符号



var price = '1,99€';
//var price = '$1,99';
var amount = Number( price.replace(/[^0-9\.]+/g,""));
var currency = price.match(/[^\d,]/g).join('');
console.log(amount);
console.log(currency);




答案 2 :(得分:0)

我认为最好的方法是使用正则表达式,这里有一个帖子:How to convert a currency string to a double with jQuery or Javascript?可以满足您的需求:

var currency = "GB$13,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));

但是不同的文化以不同的方式写小数点,有些使用逗号,有些使用句号,所以如果你必须处理这些情况,你可能需要调整表达式。

答案 3 :(得分:0)

对于全面的解决方案,我会考虑利用像money.js这样的现有库:

http://openexchangerates.github.io/money.js/

这对于现实世界的产品更合适,但我不确定您是否将此作为学习练习或其他内容。

答案 4 :(得分:0)

您可以尝试使用正则表达式进行匹配和替换

var extractMoney = function(string) {
  var amount = string.match(/[0-9]+([,.][0-9]+)?/)
  var unit = string.replace(/[0-9]+([,.][0-9]+)?/, "")
  if (amount && unit) {
    return {
      amount: +amount[0].replace(",", "."),
      currency: unit
    }
  }
  return null;
}

console.log(extractMoney("1,99€"));
console.log(extractMoney("$1,99")); 
console.log(extractMoney("error"));

结果

extractMoney("1,99€"); // => {amount: 1.99, currency: "€"}
extractMoney("$1,99"); // => {amount: 1.99, currency: "$"}
extractMoney("error"); // => null
相关问题