Last active
September 27, 2020 03:17
-
-
Save RepSklvska/3607b164886b580706269fd833a27c92 to your computer and use it in GitHub Desktop.
File size formatting - TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 传入一个B为单位的整数,返回适合在文件浏览器里显示的三位数加两位小数的大小,带单位,抹零。 | |
// 可以把整个函数的定义放进tsun命令行中进行测试 | |
// tsun安装方式:npm i -g typescript tsun | |
// 例如: | |
// 102369888 -> 97.63MB | |
// 527360 -> 515KB | |
// 4680843264 -> 4.36GB | |
const SizeConvert = (size: number): string => { | |
const X = (size: number, unit: number): string => { | |
// 我也不知道怎么描述这X函数干啥使的 | |
let a: string = (s / unit).toFixed(2); // 改成1,下面去掉三行,就是保留一位小数 | |
if (a[a.length - 1] === "0") { | |
a = a.substr(0, a.length - 1); | |
} | |
if (a[a.length - 1] === "0") { | |
a = a.substr(0, a.length - 1); | |
} | |
if (a[a.length - 1] === ".") { | |
a = a.substr(0, a.length - 1); | |
} | |
return a; | |
}; | |
const s = size; | |
if (s === 0) { | |
return "0B"; | |
} | |
if (s < 1024) { | |
return s + "B"; | |
} | |
if (s < 1048576) { | |
return Math.round(s / 1024) + "KB"; | |
} | |
if (s < 1073741824) { | |
let a: string = X(s, 1048576); | |
if (a === "1024") { return "1GB"; } | |
return a + "MB"; | |
} | |
if (s < 1099511627776) { | |
let a: string = X(s, 1073741824); | |
if (a === "1024") { return "1TB"; } | |
return a + "GB"; | |
} | |
if (s < 1125899906842624) { | |
let a: string = X(s, 1099511627776); | |
if (a === "1024") { return "1PB"; } | |
return a + "TB"; | |
} | |
if (s < 1152921504606846976) { | |
let a: string = X(s, 1125899906842624); | |
if (a === "1024") { return "1EB"; } | |
return a + "PB"; | |
} | |
{ | |
let a: string = X(s, 1125899906842624); | |
return a + "EB"; | |
} | |
}; | |
export { SizeConvert }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment