Last active
November 24, 2025 20:53
-
-
Save denwwer/2ada0c2ae237b8c4ce7e561a30b9b727 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Converts a number to a formatted string with k, m, etc. | |
| * | |
| * @param {number} num The number to format. | |
| * @param {number} [digits=1] The number of decimal places to display. Defaults to 1. | |
| * @returns {string} The formatted string. | |
| */ | |
| function formatNumber(num: number, digits: number = 1): string { | |
| if (typeof num !== 'number' || isNaN(num)) { | |
| return 'Invalid input: Not a number'; | |
| } | |
| if (num === 0) { | |
| return '0'; | |
| } | |
| let absNum = Math.abs(num); | |
| if (absNum >= 1e12) { | |
| return (absNum / 1e12).toFixed(digits) + 'T'; | |
| } else if (absNum >= 1e9) { | |
| return (absNum / 1e9).toFixed(digits) + 'B'; | |
| } else if (absNum >= 1e6) { | |
| return (absNum / 1e6).toFixed(digits) + 'M'; | |
| } else if (absNum >= 1e3) { | |
| return (absNum / 1e3).toFixed(digits) + 'k'; | |
| } else { | |
| return absNum.toFixed(0); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment