【发布时间】: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.4或10.3可能是跨不同编程语言的问题:不同的语言有different definitions of rounding。这是您的实际问题吗? -
使用该示例以与修复相同的问题结束,即索引 6 处不匹配
-
看这个:Python也有类似的问题。
-
谢谢,但是我需要在 JavaScript 中找到解决方案,所以 Python 不可用 :)
标签: javascript excel