Skip to content

Instantly share code, notes, and snippets.

@zaydek-old
Last active August 28, 2019 15:15
Show Gist options
  • Save zaydek-old/e9167716151e2d9d89846638b5e6f693 to your computer and use it in GitHub Desktop.
Save zaydek-old/e9167716151e2d9d89846638b5e6f693 to your computer and use it in GitHub Desktop.
Convert a number (integer) to a human-readable string.
// `reverse` reverses a string. `reverse` is not Unicode-
// safe.
function reverseString(str) {
return str.split("").reverse().join("")
}
// `humanReadableInteger` converts a number to a human-
// readable string. `humanReadableInteger` is not Unicode-
// safe.
//
// 1. Convert the number to a string.
// 2. Reverse the string.
// 3. Concatenate a comma per three digits (not at the end of the line).
// 4. Re-reverse the string.
function humanReadableInteger(int) {
let str = int.toString()
str = reverseString(str)
str = str.replace(/\d{3}(?!$)/g, match => match + ",")
str = reverseString(str)
return str
}
console.log(humanReadableInteger(1)) // 1
console.log(humanReadableInteger(12)) // 12
console.log(humanReadableInteger(123)) // 123
console.log(humanReadableInteger(1234)) // 1,234
console.log(humanReadableInteger(12345)) // 12,345
console.log(humanReadableInteger(123456)) // 123,456
console.log(humanReadableInteger(1234567)) // 1,234,567
console.log(humanReadableInteger(12345678)) // 12,345,678
console.log(humanReadableInteger(123456789)) // 123,456,789
console.log(humanReadableInteger(1234567890)) // 1,234,567,890
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment