【问题标题】:javascript and excel rounding wierdnessjavascript和excel舍入怪异
【发布时间】:2017-09-20 02:34:56
【问题描述】:

我有一个包含一些计算的 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

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

【问题讨论】:

  • 10.35 舍入到10.410.3 可能是跨不同编程语言的问题:不同的语言有different definitions of rounding。这是您的实际问题吗?
  • 使用该示例以与修复相同的问题结束,即索引 6 处不匹配
  • 看这个:Python也有类似的问题。
  • 谢谢,但是我需要在 JavaScript 中找到解决方案,所以 Python 不可用 :)

标签: javascript excel


【解决方案1】:

对我来说,它在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多