Question

I don't understande why this is not working: (method is taken from HERE on SO).

private String MakeSizeHumanReadable(int bytes, boolean si) {
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    String hr = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    hr = hr.replace("-1 B", "n.a.");
    return hr;
}

and neither this one:-

private String MakeSizeHumanReadable(int bytes, boolean si) {
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    String hr = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);

    Pattern minusPattern = Pattern.compile("-1 B");
    Matcher minusMatcher = minusPattern.matcher(hr);
    if (minusMatcher.find()) {
        return "n.a.";
    } else {
        return hr;
    }
}

from time to time I get -1 B from the request (this is normal), that is never changed in n.a. (....my question).

Does anyone have an idea?

Was it helpful?

Solution

Here's your problem:

if (bytes < unit) return bytes + " B";

When bytes equals -1 (which is less than unit in either case), it returns -1 B without ever getting to the line hr = hr.replace("-1 B", "n.a.");.

It would be better to have one return statement at the end, assign String hr = bytes + " B" in the if, and add an else block around the next three lines. Then after that block, the hr.replace() call will execute either way, and then return the value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top