AngularJS中使用API返回的格式化货币值执行数学运算并保留原格式
解决方案
要实现只通过formattedValue做数学运算并保留原币种格式,只需分3步处理:
- 先统一解析
formattedValue的结构,提取纯数值、币种标识、格式化规则(千分位分隔符、小数分隔符、小数位数) - 用提取出的纯数值做加法等运算
- 运算完成后,用之前提取的格式化规则和币种标识,把结果重新格式化为对应币种的显示样式
注意:需要确保参与运算的所有formattedValue为同一币种,跨币种直接求和无实际业务意义
你可以直接参考修改后的实现代码:
$scope.performMath = () => { const prices = [ { price: { formattedValue: "€ 200,00", value: "200" } }, { price: { formattedValue: "€ 400,00", value: "400" } }, { price: { formattedValue: "€ 200,00", value: "500" } }]; // 解析格式化价格的工具函数,适配全球主流币种格式 const parseFormattedPrice = (formattedStr) => { // 提取数字及分隔符部分,兼容逗号、点号、单引号等千分位/小数分隔符 const numPartMatch = formattedStr.match(/[\d,.']+/)?.[0]; if (!numPartMatch) return { pureValue: 0 }; // 提取币种前缀 const currencyPrefix = formattedStr.split(numPartMatch)[0]; // 识别小数分隔符:数字部分最后一个非数字字符为小数分隔符 const decimalSeparator = numPartMatch.match(/[,.'](?=\d*$)/)?.[0] || '.'; // 千分位分隔符为数字部分除小数分隔符外的非数字字符 const thousandsSeparator = numPartMatch.match(new RegExp(`[^\\d${decimalSeparator}]`))?.[0] || ''; // 提取小数位数 const decimalPlaces = decimalSeparator ? numPartMatch.split(decimalSeparator)[1]?.length || 2 : 2; // 转换为可运算的纯数值 const pureValue = parseFloat(numPartMatch.replaceAll(thousandsSeparator, '').replace(decimalSeparator, '.')); return { pureValue, currencyPrefix, decimalSeparator, thousandsSeparator, decimalPlaces } } // 按原币种格式还原计算结果 const formatResult = (value, formatRule) => { const fixedValue = value.toFixed(formatRule.decimalPlaces); let [integerPart, decimalPart] = fixedValue.split('.'); // 补充千分位分隔符 if (formatRule.thousandsSeparator) { integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, formatRule.thousandsSeparator); } return `${formatRule.currencyPrefix}${integerPart}${formatRule.decimalSeparator}${decimalPart}`; } const sumPrices = (prices) => { if(!prices.length) return '0'; // 取第一个价格的格式作为统一输出基准(需确保所有价格币种一致) const baseFormat = parseFormattedPrice(prices[0].price.formattedValue); const total = prices.reduce((sum, item) => { const { pureValue } = parseFormattedPrice(item.price.formattedValue); return sum + (pureValue || 0); }, 0); return formatResult(total, baseFormat); } $scope.totalItemPrice = sumPrices(prices); };
以上实现可以自动兼容欧元、美元、泰铢、菲律宾比索、瑞郎等绝大多数币种的显示格式,运算完成后会自动保留原币种的符号和展示规则,无需额外适配。
内容的提问来源于stack exchange,提问作者stellainlucem
相关产品推荐
相关产品推荐

