简体   繁体   English

如何将负字节值转换为 mb、gb 等?

[英]How to convert negative byte values to mb, gb etc.?

In my angular application I am converting bytes to MB , GB etc.在我的 angular 应用程序中,我将字节转换为MBGB等。

I am getting data from backend.我正在从后端获取数据。
I have for example: All ram, Availble Ram and Used Ram.我有例如:All ram、Availble Ram 和 Used Ram。
All values are stored as long in our case.在我们的例子中,所有的值都被存储了多久。 I am just converting these values.我只是在转换这些值。
For "Available Ram" the formula is "AllRam - UsedRam" and getting minus value is considered ok.对于“可用内存”,公式为“AllRam - UsedRam”,得到负值被认为是可以的。

But in case of negative values it is not working.但在负值的情况下,它不起作用。

Function I am using is:我正在使用的功能是:

 const SIZES = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

 formatBytes(bytes, decimals = 1) {
    for (var i = 0, r = bytes, b = 1024; r > b; i++) r /= b;         
    return `${parseFloat(r.toFixed(decimals))} ${SIZES[i]}`;
  }

Tried to add if statement with bytes < 0 but that didn't help.尝试添加字节 < 0 的if 语句,但这没有帮助。

I guess Math.abs() could solve the issue:我猜Math.abs()可以解决这个问题:

 const suffixes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], formatBytes = (n, decimals) => { const suffixIndex = suffixes.findIndex((_,i) => Math.abs(n) < 1024**i)-1 return `${((0|10**decimals*n/1024**suffixIndex)/10**decimals)} ${suffixes[suffixIndex]}` } console.log(formatBytes(-38750,2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM