UNPKG

num-beauty

Version:

An ultra lightweight module for formatting numbers into human-friendly strings

1 lines 878 B
const UNITS_SHORT_BINARY=["B","KiB","MiB","GiB","TiB","PiB","EiB"],UNITS_SHORT_DECIMAL=["B","KB","MB","GB","TB","PB","EB"],UNITS_LONG_BINARY=["Bytes","Kibibytes","Mebibytes","Gibibytes","Tebibytes","Pebibytes","Exbibytes"],UNITS_LONG_DECIMAL=["Bytes","Kilobytes","Megabytes","Gigabytes","Terabytes","Petabytes","Exabytes"];export function formatBytes(t,e={}){const{binary:i=!0,decimals:s=2,stripZeros:B=!1,locale:a="en-US",longFormat:b=!1}=e;if(0===t)return b?"0 Bytes":"0 B";const o=t<0,n=Math.abs(t),r=i?1024:1e3,y=b?i?UNITS_LONG_BINARY:UNITS_LONG_DECIMAL:i?UNITS_SHORT_BINARY:UNITS_SHORT_DECIMAL,I=Math.floor(Math.log(n)/Math.log(r)),N=Math.min(I,y.length-1),T=n/Math.pow(r,N),_=new Intl.NumberFormat(a,{minimumFractionDigits:B?0:s,maximumFractionDigits:s}).format(T),M=y[N];let m=M;b&&1!==T&&0===N?m=M:b&&1===T&&N>0&&(m=M.slice(0,-1));const S=`${_} ${m}`;return o?`-${S}`:S}