【问题标题】:AngularJS performing mathAngularJS 执行数学
【发布时间】:2021-10-22 03:35:32
【问题描述】:

我有这个范围函数,它在数据中有一个成本和一个格式化的值。该成本和格式化值来自 API。格式化的值可以是不同的货币,不仅限于欧元或美元,而是全球范围内的泰铢、PHP、瑞士法郎等。

如何执行数学运算,例如使用 formattedValue 数据而不是值数据进行加法?

我想保留我从 API 收到的任何货币的符号或格式。总和将以货币符号和格式显示在 DOM 中。

$scope.performMath = () => { 
    const prices = [
        {
          price: {
            formattedValue: "€ 200,00",
            value: "200"
          }
        },
        {
          price: {
            formattedValue: "€ 400,00",
            value: "400"
          }
        },
        {
          price: {
            formattedValue: "€ 200,00",
            value: "500"
          }
        }];
    const sumPrices = (prices) => prices.reduce((value, item) => value + (parseFloat(item.price.value) || 0), 0);
    $scope.totalItemPrice = sumPrices(prices).toFixed(2);
};    

【问题讨论】:

    标签: angular angularjs angularjs-scope


    【解决方案1】:

    虽然这可能不能直接解决您的问题,但如果您可以包含currency 代码(如USDEUR 等)和locale 值(如en-us、@987654330 @),然后有一个内置的 Javascript 对象 Intl,它有一个方法 Intl.NumberFormat() 可以将数字转换为所需的货币格式。

    这是一个例子:

    let num = 1234567.89; // This would be the result of your reducer method
    
    // --- Extract this method and make it as a globally accessible utility, if you want
    const formatNumber = (num, locale, curr) => {
      const formatOptions = {
        style: "currency",
        currency: curr
      };
    
      return Intl.NumberFormat(locale, formatOptions).format(num);
    }
    
    console.log(formatNumber(1234567.89, "en-gb", "EUR"))
    // Output: €1,234,567.89
    
    // NOTE: Both en-gb and en-GB works the same (case-insensitive)
    
    

    而不是通过预先格式化的货币字符串发送可能会妨碍您的应用程序的可扩展性。而是(如果可能)尝试通过现有 API 发送货币代码和语言环境可能会有所帮助。

    这里有两个你可能会发现有用的堆栈溢出链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      相关资源
      最近更新 更多