Skip to content

Instantly share code, notes, and snippets.

@vlad-shatskyi
Created June 7, 2014 13:38
Show Gist options
  • Save vlad-shatskyi/e8f761ede43c41a60508 to your computer and use it in GitHub Desktop.
Save vlad-shatskyi/e8f761ede43c41a60508 to your computer and use it in GitHub Desktop.
function formatSum(sum){
sum = sum.toString();
var mod = sum.length > 3 ? sum.length % 3 : 0;
console.log(mod);
// There is a bug which prints '147514' as ' 147 514', with a space at the beginning.
var res = sum.substr(0, mod) + ' ' + sum.substr(mod).replace(/(\d{3})/g, "$1 ");
return res;
}
// I can't believe there is no standard way to reverse a string.
String.prototype.reverse = function() { return this.toString().split('').reverse().join('')}
function formatSum2(sum) {
return sum.toString().reverse().replace(/(\d{3}(?!$))/g, "$1 ").reverse();
}
console.log(formatSum2(14751475)); // 14 751 475
console.log(formatSum2(147514754)); // 147 514 754
console.log(formatSum2(1475147547)); // 1 475 147 547
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment