Created
October 22, 2012 19:35
-
-
Save sillero/3933573 to your computer and use it in GitHub Desktop.
javascript - avoiding bugs in .toFixed()
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 toFixed(num, dec) { | |
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec), | |
$arr = (result+[]).split('.'), | |
$int = $arr[0] + '.', | |
$dec = $arr[1] || '0'; | |
return $int + $dec + (Math.pow(10,(dec - $dec.length))+[]).substr(1); | |
} | |
//OR | |
Number.prototype.toFixed = function(dec){ | |
var result = Math.round(this*Math.pow(10,dec))/Math.pow(10,dec), | |
$arr = (result+[]).split('.'), | |
$int = $arr[0] + '.', | |
$dec = $arr[1] || '0'; | |
return $int + $dec + (Math.pow(10,(dec - $dec.length))+[]).substr(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment