Last active
August 29, 2015 14:07
-
-
Save imazine/d610c4f8ca1ffc937737 to your computer and use it in GitHub Desktop.
JavaScript Floating point issue.
This file contains 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 actualNumber(num) { return ((num * 10000) >> 0 ) * 0.0001; } | |
function actualNatural(num) { return parseInt(num * 10000) * 0.0001; } | |
function actualCasting(num) { return parseFloat(num.toFixed(4)); } | |
function test(number, iterator){ | |
console.log('----------------------------------------------'); | |
console.log('Test method : ', iterator); | |
var start = performance.now(); | |
console.log('test start at : ' + start); | |
for (var i = 0; i < 1000000; i++ ) { | |
iterator(number); | |
} | |
var end = performance.now(), | |
elapsed = end - start; | |
console.log('test end at : ' + end); | |
console.log('Test result : ', iterator(number)); | |
console.log('time elapsed : ', elapsed, 'ms'); | |
console.log('----------------------------------------------'); | |
} | |
function testMain(){ | |
var num = 0.1 * 0.1; | |
console.log('number: 0.1 * 0.1 = ', num); | |
test(num, actualCasting); | |
test(num, actualNatural); | |
test(num, actualNumber); | |
var num = 1000.1 * 1000.1; | |
console.log('number: 1000.1 * 1000.1 = ', num); | |
test(num, actualCasting); | |
test(num, actualNatural); | |
test(num, actualNumber); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment