Created
April 29, 2020 09:11
-
-
Save sofish/cd38e55e82d6d48146e92f4afeae90c0 to your computer and use it in GitHub Desktop.
0.1 + 0.2 = 0.3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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