UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

49 lines (47 loc) 1.2 kB
/** * 格式化 bite 单位,最多保留2位小数,最大单位为BB * @param size bite 单位 * @param options 配置项(可选) * @returns 格式化的字符 * * @example * * formatBite(1) * // 1B * * formatBite(100) * // 100B * * formatBite(1000) * // 1000B * * formatBite(10000) * // 9.77KB * * formatBite(10000, { space: true }) * // '9.77 KB' * * formatBite(10000, { fixed: 1 }) * // '9.8KB' * * formatBite(10000, { space: true, fixed: 1 }) * // '9.8 KB' */ function formatBite(size) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var UNIT = 1024; var UNIT_LIST = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB']; var _options$space = options.space, space = _options$space === void 0 ? false : _options$space, _options$fixed = options.fixed, fixed = _options$fixed === void 0 ? 2 : _options$fixed; var res = size; var loopTime = 0; while (res > UNIT && loopTime < UNIT_LIST.length - 1) { res = res / UNIT; loopTime += 1; } var num = parseFloat(res.toFixed(fixed)); return "".concat(num).concat(space ? ' ' : '').concat(UNIT_LIST[loopTime]); } export { formatBite };