正确格式化Android TrafficStats值的问题

时间:2013-06-13 18:23:20

标签: java

我试图格式化一个trafficstats值,使其显示为12.22 MB(而不是现在显示的12.00000)但是我在使用以下方法时不断获得强制关闭错误:

String.format("%1$,.2f", info);
info += ("\tWifi Data Usage: " + (double) (TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes() - (TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes())) / 1000000  + " MB");
info += ("\tMobile Data Usage: " + (double) (TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes()) / 1000000  + " MB");

P.S。

我还试图使用以下方法(在下面的第一个答案之后)

NumberFormat nf= new NumberFormat();
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);

        String result= nf.format(info);

但是它会导致:"无法实例化NumberFormat"虽然import java.text.NumberFormat;被称为

2 个答案:

答案 0 :(得分:2)

使用NumberFormat

NumberFormatabstract,这意味着您无法按原样实例化它。您需要使用NumberFormat.getInstance方法,它将为您创建一个匿名的具体子类,或者自己实例化一个具体的实例。你可能想要第二种方式,看起来像这样:

// DecimalFormat is a concrete subclass of NumberFormat.
NumberFormat nf = new DecimalFormat("#.##"); // Set the format to "#.##"

String result = nf.format(11.987654321); // result is now the String "11.99"

您可以通过更改传递给DecimalFormat构造函数的格式字符串来更改格式。这里的示例将给出两个小数位,但整个规范也可用in the docs

我还要清理你的开始部分,使它们更清晰,更容易阅读。这是一个简单的重写,每一步都明确规定:

String info = "";
double mobileMB = (TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes() / 1000000.0);
double totalMB = ((TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes()) / 1000000.0) - mobileMB;

NumberFormat nf = new DecimalFormat("#.##");
String totalMBString = nf.format(totalMB);
String mobileMBString = nf.format(mobileMB);

info += String.format("\tWifi Data Usage: %sMB\tMobile Data Usage: %s", 
        totalMBString, mobileMBString);

使用String.format

您还有其他选择。由于这是一个非常简单的应用程序,String.format的数字格式选项可能比NumberFormat的全部功能更容易使用。在这种情况下,你会想要做这样的事情:

info += String.format("\tWifi Data Usage: %.2fMB", /* Put a number in here */);
info += String.format("\tMobile Data Usage: %.2fMB" /* Put the other number in here */);

这种方式总是会产生两位小数,因此您将获得12.00MB而不是12MB

答案 1 :(得分:0)

这很快变成了一团糟。将代码和Henry的代码拼凑在一起应该可以工作并看起来像这样......

double totalBytes = (double) TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;

NumberFormat nf = new DecimalFormat("#.##");
String totalStr = nf.format(totalBytes);
String mobileStr = nf.format(mobileBytes);
String info = String.format("\tWifi Data Usage: %s MB\tMobile Data Usage, %s", totalStr, mobileStr);

信息应包含您正在寻找的字符串。