javascript和excel舍入wierdness

时间:2017-09-20 02:34:56

标签: javascript excel

我有excel表包含一些计算,我需要将其移植到javascript,但我发现一个真正令人头疼的值,因为值不匹配。

简而言之,数字需要显示为## 0.0(单个十进制),但任何尝试达到excel中显示的相同值都是失败。

测试脚本:

var excelReal = [60.78,51.05,36.14,30.93,21.65,14.76,10.35,7.64,5.51,3.82,2.44];
var excelFormat = [60.8,51.0,36.1,30.9,21.6,14.8,10.4,7.6,5.5,3.8,2.4];

console.log('Formatted values from excel:');
printArray(excelReal);
console.log('Single decimal formated from excel:');
printArray(excelFormat);
console.log('Using toFixed');
var fixed =iterate(excelReal,function(i){return i.toFixed(1);}); 
printArray(fixed);
compareArray(excelFormat,fixed);
console.log('Using custom round');
var r = iterate(excelReal,function(i){return round(i,1);});
printArray(r);
compareArray(excelFormat,r);

function printArray(what) {
    var out = '';
    for(ix=0;ix < what.length;ix++) {
        out+=what[ix] + ' ';
    }
    console.log(out);
}
function compareArray(what,withWhat) {
    for(var ix=0;ix < what.length;ix++) {
        if (what[ix]!=withWhat[ix]) console.log(what[ix] + ' ' + withWhat[ix] + ' not matching,index: ' + ix);
    }
}
function iterate(input,f)
{
    var out = [];
    for(ix=0;ix<input.length;ix++) {
        out.push(f(input[ix]));
    }
    return out;
}
function round(value, decimals) {
    return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}  

输出将是: 来自excel的原始值:

60.78 51.05 36.14 30.93 21.65 14.76 10.35 7.64 5.51 3.82 2.44

从excel格式化的单个小数:

60.8 51 36.1 30.9 21.6 14.8 10.4 7.6 5.5 3.8 2.4

使用toFixed

60.8 51.0 36.1 30.9 21.6 14.8 10.3 7.6 5.5 3.8 2.4

10.4 10.3不匹配,索引:6

使用自定义回合

60.8 51.1 36.1 30.9 21.7 14.8 10.4 7.6 5.5 3.8 2.4

51 51.1不匹配,索引:1

21.6 21.7不匹配,索引:4

任何想法如何解决这个问题....

1 个答案:

答案 0 :(得分:0)

对我来说,它在excel中正常工作。也许您提供的值不是确切的数字,而是格式化的数字。

Data    As per You in excel My Value after =ROUND(A2,1) and like that
60.78   60.8                      60.8
51.05   51                        51.1
36.14   36.1                      36.1
30.93   30.9                      30.9
21.65   21.6                      21.7
14.76   14.8                      14.8
10.35   10.4                      10.4
7.64    7.6                        7.6
5.51    5.5                        5.5
3.82    3.8                        3.8
2.44    2.4                        2.4

https://drive.google.com/file/d/0Bz49ZLVCmFjeQTI4UFNxMHBhTHc/view?usp=sharing