Skip to content

Instantly share code, notes, and snippets.

@alexmaze
Last active April 14, 2017 01:53
Show Gist options
  • Save alexmaze/275230ad21bff6c2932831f1c6a55e28 to your computer and use it in GitHub Desktop.
Save alexmaze/275230ad21bff6c2932831f1c6a55e28 to your computer and use it in GitHub Desktop.
单位转换
export class UnitConvertUtil {
/**
* 文件大小 例如 1024 -> 1 MB
*
* @param {*} value
* @param {number} fix
* @param {string} [base]
* @returns
*
* @memberOf UnitConvertUtil
*/
toFilesize(value: any, fix: number, base?: string) {
return this.sizeFormatter(value, fix, base, 'B', 1024);
}
/**
* 带宽 例如 1024 -> 1 Mbps
*
* @param {*} value
* @param {number} fix
* @param {string} [base]
* @returns
*
* @memberOf UnitConvertUtil
*/
toBandwidth(value: any, fix: number, base?: string) {
return this.sizeFormatter(value, fix, base, 'bps', 1024);
}
/**
* 流量 例如 1024 -> 1 Mb
*
* @param {*} value
* @param {number} fix
* @param {string} [base]
* @returns
*
* @memberOf UnitConvertUtil
*/
toFlow(value: any, fix: number, base?: string) {
return this.sizeFormatter(value, fix, base, 'b', 1024);
}
/**
* 数字 例如 1000 -> 1 M
*
* @param {*} value
* @param {number} fix
* @returns
*
* @memberOf UnitConvertUtil
*/
toCount(value: any, fix: number) {
return this.sizeFormatter(value, fix, undefined, undefined, 1000);
}
/**
* 百分比 例如 1.349 -> 1.35%
*
* @param {*} value
* @param {number} fix
* @returns
*
* @memberOf UnitConvertUtil
*/
toPercent(value: any, fix: number = 2) {
let val = parseFloat(value);
if (val >= 0) {
return val.toFixed(fix) + '%';
} else {
return '';
}
}
/**
* 数字转换 例如 1024 -> 1 M
*
* @export
* @param {*} value 输入数字
* @param {number} [fix=2] 小数点后保存位数
* @param {string} [base=undefined] 默认量级 K | M | G | T | P | E
* @param {string} [unit=undefined] 默认单位
* @returns
*/
sizeFormatter(value: any, fix: number = 2, base: string, unit: string = '', gap: number = 1024) {
let val = parseFloat(value);
let unitIndex;
const units = ['', 'K', 'M', 'G', 'T', 'P', 'E'];
if (base) {
unitIndex = units.indexOf(base);
} else {
unitIndex = 0;
}
while (unitIndex < units.length - 1 && val >= gap) {
val /= gap;
unitIndex++;
}
if (Math.floor(val) < val) {
val = val.toFixed(fix) as any;
}
return `${val} ${units[unitIndex]}${unit}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment