Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

格式化字节数 #42

Open
varHarrie opened this issue Apr 25, 2022 · 0 comments
Open

格式化字节数 #42

varHarrie opened this issue Apr 25, 2022 · 0 comments
Milestone

Comments

@varHarrie
Copy link
Owner

varHarrie commented Apr 25, 2022

function clamp (value: number, min: number, max: number) {
  return Math.max(min, Math.min(max, value))
}

function formatBytes(bytes: number) {
  const units = ['Bytes', 'KB', 'MB', /** 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' */];

  const k = 1024;
  const i = clamp(Math.floor(Math.log(bytes) / Math.log(k)), 0, units.length - 1);
  const v = parseFloat((bytes / Math.pow(k, i)).toFixed(2))

  return `${v} ${units[i]}`;
}

console.log(formatBytes(0));        // 0 Bytes
console.log(formatBytes(1024));     // 1 KB
console.log(formatBytes(20000000)); // 19.07 MB
@varHarrie varHarrie added this to the Snippets milestone Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant