Created
March 12, 2018 23:00
-
-
Save yishn/2b288579066e6d8eb2f5d7b676d45f80 to your computer and use it in GitHub Desktop.
Pretty print money amounts
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
exports.amount = function(amount) { | |
if (isNaN(amount)) return exports.amount(0) | |
if (amount < 0) return `-${exports.amount(-amount)}` | |
let result = (Math.round(amount * 100) + '').padStart(3, '0') | |
let [number, float] = [result.slice(0, -2), result.slice(-2)] | |
let thousands = [] | |
for (let i = 1; -3 * i >= -number.length; i++) { | |
thousands.unshift(number.slice(-3 * i, (-3 * i + 3) || undefined)) | |
} | |
let residue = number.length % 3 | |
if (residue > 0) thousands.unshift(number.slice(0, residue)) | |
return `${thousands.join('.')},${float} €` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment