Skip to content

Instantly share code, notes, and snippets.

@Erushenko
Created December 15, 2020 16:39
Show Gist options
  • Save Erushenko/cd8efb3088f4294ae86c8e1f00e2fddc to your computer and use it in GitHub Desktop.
Save Erushenko/cd8efb3088f4294ae86c8e1f00e2fddc to your computer and use it in GitHub Desktop.
format money
function formatMoney(value) {
const preparedValue =
typeof value === 'undefined' || value === null ? '' : value.toString()
let [dollars, cents = ''] = preparedValue.replace(/[^0-9.-]/g, '').split('.')
dollars = dollars.replace(/^0+/, '') || '0'
cents = `${cents}00`.slice(0, 2)
return `${dollars}.${cents}`.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment