gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:26:32 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com