Skip to content

Instantly share code, notes, and snippets.

@yishn
Created March 12, 2018 23:00
Show Gist options
  • Save yishn/2b288579066e6d8eb2f5d7b676d45f80 to your computer and use it in GitHub Desktop.
Save yishn/2b288579066e6d8eb2f5d7b676d45f80 to your computer and use it in GitHub Desktop.
Pretty print money amounts
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