num-beauty
Version:
An ultra lightweight module for formatting numbers into human-friendly strings
1 lines • 1.49 kB
JavaScript
import{locales}from"../locales/index.js";export function unbeautify(e,t={}){const r=t.locale||"en-US",i=locales[r];let s=String(e).trim();if(!s||""===s)return 0;let o=!1;s.includes("%")&&(o=!0,s=s.replace("%","").trim());let l=!1;s.startsWith("(")&&s.endsWith(")")&&(l=!0,s=s.slice(1,-1).trim()),s.startsWith("-")&&(l=!0,s=s.slice(1).trim());const c={...i.currencies};for(const e in c){const t=c[e];t&&t.symbol&&(s=s.replace(t.symbol,"").trim()),s=s.replace(new RegExp(`\\b${e}\\b`,"gi"),"").trim()}let n=1;const a=i.units||[],m={tib:1024**4,gib:1024**3,mib:1048576,kib:1024,tb:1024**4,gb:1024**3,mb:1048576,kb:1024},b=s.toLowerCase();for(const[e,t]of Object.entries(m))if(b.endsWith(e)){n=t,s=s.slice(0,-e.length).trim();break}if(1===n)for(let e=a.length-1;e>=0;e--){const t=a[e];if(t){for(const r of t)if(r&&s.toLowerCase().endsWith(r.toLowerCase())){n=Math.pow(1e3,e),s=s.slice(0,-r.length).trim();break}if(1!==n)break}}if(1===n){const e={t:1e12,b:1e9,m:1e6,k:1e3},t=s.slice(-1).toLowerCase(),r=s.slice(-2,-1);e[t]&&/[\d\s]/.test(r||" ")&&"."!==r&&","!==r&&(n=e[t],s=s.slice(0,-1).trim())}const f=new Intl.NumberFormat(r).format(1.1).charAt(1),p=new Intl.NumberFormat(r).format(1e3).charAt(1);p&&"."!==p?s=s.replace(new RegExp(`\\${p}`,"g"),""):"."===p&&"."!==f&&(s=s.replace(f,"DECIMAL_PLACEHOLDER"),s=s.replace(/\./g,""),s=s.replace("DECIMAL_PLACEHOLDER",".")),"."!==f&&(s=s.replace(f,".")),s=s.replace(/[^\d.-]/g,"");let g=parseFloat(s);return isNaN(g)?0:(g*=n,o&&(g/=100),l&&(g=-g),g)}