2

I would like to know the Total Internal Memory and write it in a Preference so I wrote this code:

 File path = Environment.getDataDirectory();
 StatFs stat = new StatFs(path.getPath());
 long blockSize = stat.getBlockSize();
 long totalBlocks = stat.getBlockCount();
 long Size = totalBlocks * blockSize/1073741824;

 memory = (Preference) this.findPreference("free");
 memory.setSummary(Long.toString(Size)+" GB");

1073741824 corresponds to 1024*1024*1024 for obtaining teh GigaByte. Now, the problem is, why the result is an integer? For example, in the Preference is written "5" but if I do the calculation and divide the variable size for 1024/1024 i get 5393 and which is divided again by 1024 is 5,26, but since then I receive only 5 as outpout? How can I fix this?

gunar
  • 14,392
  • 7
  • 54
  • 83
Mario G.
  • 393
  • 1
  • 3
  • 14

2 Answers2

3

long variables can only hold long integers. You have to use a floating point type instead. For example:

double size = totalBlocks * blockSize / 1073741824d;

Another point to make sure is that at least one of the operands in your calculation is also a floating point type (see the d suffix to the constant). Otherwise Java will calculate an integer value and assign it to the double variable.

Furthermore, by convention, your variables should not start with a capital letter. This style is reserved for type names.

Chriki
  • 7,999
  • 3
  • 37
  • 55
  • Thanks! It Works but now i see a number as 13,328445434570313How can I get only the first decimal place? – Mario G. Nov 27 '13 at 15:41
  • One possibility to round to the first decimal place: `size = Math.round(size * 10) / 10d` ([via](http://stackoverflow.com/a/153753/1797912)) – Chriki Nov 27 '13 at 15:49
  • @Mario G. Glad I could help! If you found my answer useful, then please consider marking it as the accepted answer. – Chriki Nov 27 '13 at 15:56
-1

Do the division declaring the GB long as a float

long Size = totalBlocks * blockSize/1073741824f;
Noah
  • 1,916
  • 1
  • 14
  • 29
  • 2
    Unless you change the type of `Size` from `long` to `float` or `double`, it's still going to end up as `5`. – Geobits Nov 27 '13 at 15:38
  • Missed that you declared the size as a long. Use a double or float to store the result. See other answer. :) – Noah Nov 27 '13 at 15:43