Skip to content

Instantly share code, notes, and snippets.

@thiagomr
Last active January 16, 2018 19:09
Show Gist options
  • Select an option

  • Save thiagomr/c4e1a559048ad1518625225ca43d8fb2 to your computer and use it in GitHub Desktop.

Select an option

Save thiagomr/c4e1a559048ad1518625225ca43d8fb2 to your computer and use it in GitHub Desktop.
function numberToMoney(fixed = 2, value) {
if (!value || typeof value != 'number') {
throw new Error("´value´ is not set");
}
let formatted = value.toFixed(fixed).replace('.', ',').split(',');
let final = [];
if (formatted[0].length > 3) {
for (let i = formatted[0].length - 1; i >= 0; i--) {
final.push(formatted[0][i]);
if ((formatted[0].length - i) % 3 == 0 && (formatted[0].length - i) != formatted[0].length) {
final.push('.');
}
}
final = final.reverse().join("").concat(',' + formatted[1]);
} else {
final = formatted[0].concat(',' + formatted[1]);
}
return final;
}
console.log(numberToMoney(4, 1000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment