I have excel sheet that contains some calculations, i need to port this to javascript, but i have discovered a real headache as values do not match.
In short, numbers need to presented as ##0.0 (single decimal) but any attempt to reach same value shown in excel is a failure.
Test script:
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);
}
Output will be: Original values from excel:
60.78 51.05 36.14 30.93 21.65 14.76 10.35 7.64 5.51 3.82 2.44
Single decimal formated from excel:
60.8 51 36.1 30.9 21.6 14.8 10.4 7.6 5.5 3.8 2.4
Using 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 not matching,index: 6
Using custom round
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 not matching,index: 1
21.6 21.7 not matching,index: 4
Any ideas how to fix this ....