Convert Long to Decimal

I tried to find a solution for this, but I just can't. I want to show a megabyte long representation, which is calculated in bytes.

In Java, you got a length () method that you can call on a file object. It will return the size of the files in bytes stored in long. Now I want so long and turn it into megabytes, not bytes. The file I'm trying to get is 161,000 bytes in size. If I'm not mistaken, this translates to 0.161 megabytes. So I would make bytes / 100000, and I would expect to get 0.161. The problem is that I do not.

If I go to my Windows calculator or any other calculator, the application will be able to show these 3 decimal places. Why can't I do this? I tried storing the result in a double that just appears as 0.0

EDIT: Answers found. Thanks wrm:

long b = file.length (); double mb = (double) b / (1024 * 1024);

+4
source share
5 answers

Perhaps a little code will clarify the problem, but I think you have some kind of implicit conversion. something like this should work:

double result = (double)myLongVal / 1024.0; 
+5
source

You need to convert one of the arguments to double, not just the result.

Try sharing instead of 1000000.0 .

+3
source

What you are doing wrong is using Integral divsion, where you need to use floating point.

If both of your openings are integers (long and int), you get the result in the form of eegral, that is, it will not have a decimal part.

If you want to have a decimal division, at least one of your gangs should float or muzzle. you will get this by adding .0 to the literal number or using a typed variable.

I would also suggest using the BigDecimal class, which will always give the correct result, since longs and doubles can not represent all decimal numbers in their ranges. (they have limited accuracy)

+2
source

You can take a look at the DecimalFormat Class and format the result as you like.

 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); 
+1
source
 Long size1 = size / 1000; double value = (double) size1; String str = String.valueOf(value); 

It has done the magic for us.

0
source

Source: https://habr.com/ru/post/1412356/


All Articles