Files
qiming/qiming-mobile/utils/byteConverter.uts

60 lines
1.7 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 将字节Byte转换为适当的单位KB, MB, GB, TB
* @param bytes 字节数
* @param decimals 小数点后位数
* @returns 格式化后的字符串
*/
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return (
Number.parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
);
}
/**
* 将字节转换为千字节KB
* @param bytes 字节数
* @param decimals 小数点后位数
* @returns 千字节数值
*/
export function bytesToKB(bytes: number, decimals = 2): number {
return Number.parseFloat((bytes / 1024).toFixed(decimals));
}
/**
* 将字节转换为兆字节MB
* @param bytes 字节数
* @param decimals 小数点后位数
* @returns 兆字节数值
*/
export function bytesToMB(bytes: number, decimals = 2): number {
return Number.parseFloat((bytes / (1024 * 1024)).toFixed(decimals));
}
/**
* 将字节转换为千字节KB并格式化
* @param bytes 字节数
* @param decimals 小数点后位数
* @returns 格式化后的千字节字符串
*/
export function formatBytesToKB(bytes: number, decimals = 2): string {
return `${bytesToKB(bytes, decimals)} KB`;
}
/**
* 将字节转换为兆字节MB并格式化
* @param bytes 字节数
* @param decimals 小数点后位数
* @returns 格式化后的兆字节字符串
*/
export function formatBytesToMB(bytes: number, decimals = 2): string {
return `${bytesToMB(bytes, decimals)} MB`;
}