Skip to content

Instantly share code, notes, and snippets.

@sofish
Created April 29, 2020 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofish/cd38e55e82d6d48146e92f4afeae90c0 to your computer and use it in GitHub Desktop.
Save sofish/cd38e55e82d6d48146e92f4afeae90c0 to your computer and use it in GitHub Desktop.
0.1 + 0.2 = 0.3
function big(n, m) {
var a1 = f(n), a2 = f(m);
var overflow = d(a1[1], a2[1]);
arr = [a1[0] + a2[0] + overflow[0], overflow[1]];
return +arr.join('.');
}
function f(n) {
var tmp = ('' + n).split('.');
if(tmp.length === 1) tmp[1] = '0';
tmp[0] = +tmp[0];
return tmp;
}
function d(a, b) {
var l = Math.max(a.length, b.length);
var r = +a + (+b);
var base = Math.pow(10, l);
return [r >= base ? 1 : 0, r % base];
}
var normal = 0, modified = 0;
for(var i = 0; i < 1e7; i++) {
normal += 0.1 + 0.2;
modified = big(modified, big(0.1, 0.2));
}
console.log(normal, modified);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment