我需要在我的应用程序中将字节转换为兆字节,但出了点问题..首先,我需要显示例如1.2MB而不是1MB..现在,我有这个声明:
public long mStartRX = 0;
然后在onCreate中
mStartRX = TrafficStats.getTotalRxBytes();
最后可以找到以字节为单位的数据使用情况:
final long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes) + " " + "Bytes");
我尝试了这个解决方案:
final long rxBytes = TrafficStats.getTotalRxBytes()/(1024*1024)- mStartRX;
RX.setText(Long.toString(rxBytes) + " " + "Bytes");
但结果不正确。事实上,我显示的内容类似于:-1258912654
,当然它不正确。我该如何解决这个问题?
最佳答案
我认为这需要一些数学技能,还需要整数/浮点除法的知识。但这段代码应该可以工作
long mStartRX = TrafficStats.getTotalRxBytes();
...
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(rxBytes + " Bytes");
RX.setText(String.format("%.2f MB",rxBytes /(1024f*1024f)));
String.format 用于从浮点变量/表达式中精确获取 2 位小数 (%.2f)。另外,“1024f”表示浮点型 1024,因为我们需要浮点除法,而不是整数除法。
编辑
将其保存在变量中
float rxMBytes = rxBytes/(1024f*1024f);
RX.setText(String.format("%.2f MB",rxMBytes ));
关于java - 字节到兆字节的转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19914664/