Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Created September 3, 2012 10:06
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 nfroidure/3608274 to your computer and use it in GitHub Desktop.
Save nfroidure/3608274 to your computer and use it in GitHub Desktop.
Convert a number to an amount
Number.prototype.toAmount = function() {
var parts=(this+'').split('.');
parts[0]=(parts[0]?parts[0]:'0');
parts[1]=(parts[1]?parts[1].substring(0,2):'00');
parts[1]+=(parts[1].length==1?'0':'');
return parts[0]+'.'+parts[1];
}
var price=12.112;
console.log(price.toAmount()); // Outputs 12.11
var price=12.12;
console.log(price.toAmount()); // Outputs 12.12
var price=12.1;
console.log(price.toAmount()); // Outputs 12.10
var price=0.1;
console.log(price.toAmount()); // Outputs 0.10
var price=0;
console.log(price.toAmount()); // Outputs 0.00
var price=-0.1;
console.log(price.toAmount()); // Outputs -0.10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment