Created
September 3, 2012 10:06
-
-
Save nfroidure/3608274 to your computer and use it in GitHub Desktop.
Convert a number to an amount
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
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