无论格式如何,对数字求和正确

Sum numbers right, no matter the format

本文关键字:数字 求和 格式      更新时间:2023-09-26

我有这个函数,它总和的正则表达式结果:

'use strict';
function sum(string) {
    var match, result, pattern;
    pattern = /['d,'.]+/g
    match = string.match(pattern);
 
    if (!match.length) {
      return 'Didn''t find any trace.';
    }
    result = match.reduce(function(prev, curr) {
      curr = curr.replace(/'./g, '').replace(',', '.');
      return prev + (+curr);
    }, 0);
    if (!isNaN(result)) {
      return result;
    } else {
      return 'The sum fails.';
    }
}
console.log(sum('156,02 10')); // expected: 166.02 = works
console.log(sum('10.10 10.10')); // expected: 20.20 = doesn't work, result = 2020
console.log(sum('01.10 2,30')); // expected: 3.40 = doesn't work, result = 112.3

并且仅在我拥有 152,02 格式时才有效。我希望它接受所有格式。可能吗?没有任何库可以提供帮助?

谢谢。

尝试使用删除.replace(/'./g, ''),包括+运算符,在prev之前转换为prev字符串到Number

'use strict';
function sum(string) {
    var match, result, pattern;
    pattern = /('d+'.'d+)|('d+,'d+)|('d+)/g;
    match = string.match(pattern);
 
    if (!match.length) {
      return 'Didn''t find any trace.';
    }
    result = match.reduce(function(prev, curr) {
      curr = curr.replace(',', '.');
      return +prev + (+curr);
    }, 0);
    if (!isNaN(result)) {
      return result;
    } else {
      return 'The sum fails.';
    }
}
console.log(sum('156,02 10')); // expected: 166.02 = works
console.log(sum('10.10 10.10')); // expected: 20.20 = doesn't work, result = 2020
console.log(sum('01.10 2,30')); // expected: 3.40 = doesn't work, result = 112.3