UNPKG

numify

Version:

Shortern long numbers to Human Readable K M B format

2 lines (1 loc) 1.48 kB
const e={en:{decimal:".",thousand:",",system:"international"},de:{decimal:",",thousand:".",system:"international"},fr:{decimal:",",thousand:" ",system:"international"},es:{decimal:",",thousand:".",system:"international"},in:{decimal:".",thousand:",",system:"indian"},it:{decimal:",",thousand:".",system:"international"},ch:{decimal:".",thousand:"'",system:"international"},se:{decimal:",",thousand:" ",system:"international"}},n={k:"thousand",M:"million",B:"billion",T:"trillion",E:"quintillion",P:"quadrillion",Cr:"crore",L:"lakh"},t=n=>n?"international"===n||"indian"===n?{decimal:".",thousand:",",system:n}:e[n]||e.en:e.en,i=(e,i={})=>{const{formatType:a="en",precise:s=!1,style:o="short",units:l}=i;e=Number(e.toString().replace(/[^0-9.]/g,""));const r=t(a);if(e<1e3)return s?e.toFixed(2).replace(".",r.decimal):e.toString()+(l?1===e?` ${l[0]}`:` ${l[1]}`:"");let d;d=l?[[1,1===e?l[0]:l[1]]]:"indian"===r.system?[[1e7,"Cr"],[1e5,"L"],[1e3,"K"]]:[[1e18,"E"],[1e15,"P"],[1e12,"T"],[1e9,"B"],[1e6,"M"],[1e3,"k"]];const c=d.find((([n])=>e>=n));if(!c)return e.toString()+(l?1===e?` ${l[0]}`:` ${l[1]}`:"");const m=(e/c[0]).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/,"$1").replace(".",r.decimal),u="long"!==o||l?c[1]:` ${n[c[1]]}`;return m+(l?1===e?` ${l[0]}`:` ${l[1]}`:u)},a=(e,n={})=>{const{formatType:i="en"}=n,a=t(i),s=e.toString().split(".");return s[0]=s[0].replace(/\B(?=(\d{3})+(?!\d))/g,a.thousand),s.length>1?s.join(a.decimal):s[0]};export{a as formatNumber,i as numify};