Skip to content

Instantly share code, notes, and snippets.

@sillero
Created October 22, 2012 19:35
Show Gist options
  • Save sillero/3933573 to your computer and use it in GitHub Desktop.
Save sillero/3933573 to your computer and use it in GitHub Desktop.
javascript - avoiding bugs in .toFixed()
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