Created
October 31, 2012 22:50
-
-
Save Foodguru/3990471 to your computer and use it in GitHub Desktop.
javascript: number to currency. Rails like
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 number_to_currency(number, options) { | |
try { | |
var options = options || {}; | |
var precision = options["precision"] || 2; | |
var unit = options["unit"] || "$"; | |
var separator = precision > 0 ? options["separator"] || "." : ""; | |
var delimiter = options["delimiter"] || ","; | |
var parts = parseFloat(number).toFixed(precision).split('.'); | |
return unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString(); | |
} catch(e) { | |
return number; | |
} | |
} | |
function number_with_delimiter(number, delimiter, separator) { | |
try { | |
var delimiter = delimiter || ","; | |
var separator = separator || "."; | |
var parts = number.toString().split('.'); | |
parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter); | |
return parts.join(separator); | |
} catch(e) { | |
return number | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment