Reputation: 5709
I've tried to look around for a solution to this, but I simply can't. I want to show the megabyte representation of a long that is calculated in bytes.
In Java, you got a method called length() that you can invoke on a file object. It will return the files size in bytes stored in a long. Now, I want to that long and turn it into megabytes rather than bytes. A file I am trying with got the size 161000 bytes. If I am not mistaken, that translates to 0.161 megabytes. So I would do bytes / 100000 and I would expect to get 0.161. The problem is that I don't.
If I go to my Windows Calculator, or any other calculator for that matter, the application can manage to show those 3 decimals. Why is it that I can't do this? I tried to store the result in a double, which just comes out as 0.0
EDIT: An answers has been found. Thanks to wrm:
long b = file.length(); double mb = (double) b / (1024 * 1024);
Upvotes: 7
Views: 31604
Reputation: 462
Long size1 = size / 1000;
double value = (double) size1;
String str = String.valueOf(value);
This did the magic to us.
Upvotes: 0
Reputation: 4715
What you do wrongis that you use Integral divsion, where you need to use floating point one.
If both your opernads are integral (long and int) you get inegral result - i.e. it will have no decimal part.
If you want to have decimal divison, at least one of your opernads has to bee float or doule. you get that by adding .0 to literal number, or using typed variable.
I would also suggest using BigDecimal class that will allways yield correct result, for longs and doubles cant represent all decimal numbers in their ranges. (they have limited precision)
Upvotes: 2
Reputation: 52185
You could take a look at the DecimalFormat Class and format your result as how you wish.
double value = size / 1000.0;
DecimalFormat df = new DecimalFormat("#.##"); //This should print a number which is rounded to 2 decimal places.
String str = df.parse(value);
Upvotes: 1
Reputation: 1908
maybe a little code would clarify the problem but i think, you have some kind of implicit conversion going on. something like this should work:
double result = (double)myLongVal / 1024.0;
Upvotes: 10
Reputation: 11597
You need to convert one of the arguments to a double, not just the result.
Try dividing by 1000000.0
instead.
Upvotes: 4