java - 字节到兆字节的转换不起作用

标签 java android megabyte

我需要在我的应用程序中将字节转换为兆字节,但出了点问题..首先,我需要显示例如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/

相关文章:

java - 函数内的多线程变量访问

java - 与通过 android studio 安装相比,作为 APK 安装时,Retrofit 的行为不同且无法解析

java - List.iterator() 是线程安全的吗?

java - 上下文需要 FLAG_ACTIVITY_NEW_TASK 但我已经设置了该标志

android - android 中的 Activity 与 Fragment

Android - 存储下次启动时保留和使用的游戏状态信息

MySQL 将字节转换为千字节、兆字节、千兆字节

java - Android中自定义键盘 "enter"按钮