Created
March 3, 2019 16:59
-
-
Save leongaban/cd34575d2d0fcfc328347430f8938c55 to your computer and use it in GitHub Desktop.
Large currency / money number formatter
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
// https://tinyurl.com/nFormatter | |
export const nFormatter = (num: number, digits: number) => { | |
const si = [ | |
{ value: 1, symbol: "" }, | |
{ value: 1E3, symbol: "k" }, | |
{ value: 1E6, symbol: "M" }, | |
{ value: 1E9, symbol: "G" }, | |
{ value: 1E12, symbol: "T" }, | |
{ value: 1E15, symbol: "P" }, | |
{ value: 1E18, symbol: "E" } | |
]; | |
const rx = /\.0+$|(\.[0-9]*[1-9])0+$/; | |
let i; | |
for (i = si.length - 1; i > 0; i--) { | |
if (num >= si[i].value) { | |
break; | |
} | |
} | |
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol; | |
} | |
/* | |
nFormatter(100000000, 1) = 100M | |
nFormatter(299792458, 1) = 299.8M | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment