Byte to megabyte conversion doesn't work

535 views Asked by At

i need convert the byte in Megabyte in my application but something is wrong.. First of all, i need display for example 1.2MB and not 1MB.. now, i have this declaration:

public long mStartRX = 0;

then in the onCreate

mStartRX = TrafficStats.getTotalRxBytes();

finally this to find the data usage in byte:

final long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
        RX.setText(Long.toString(rxBytes) + " " + "Bytes");

i tryied this solution:

final long rxBytes = TrafficStats.getTotalRxBytes()/(1024*1024)- mStartRX;
        RX.setText(Long.toString(rxBytes) + " " + "Bytes");

but the result is not correct.. Infact i display something like: -1258912654 and of course it's not correct. How can i solve the problem?

1

There are 1 answers

4
hakanostrom On BEST ANSWER

It takes some math skills here I think, and also knowledge of integer/floatingpoint division. But this code should work

long mStartRX = TrafficStats.getTotalRxBytes();
...
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;

RX.setText(rxBytes + " Bytes");
RX.setText(String.format("%.2f MB",rxBytes /(1024f*1024f)));

The String.format is used to get exactly 2 decimals (%.2f) from a floating point varible/expression. Also "1024f" means 1024 in float, because we want floating point division, not integer division.

Edit

To save it in variable

float rxMBytes = rxBytes/(1024f*1024f);
RX.setText(String.format("%.2f MB",rxMBytes ));