-2

I was having some problem when trying to convert bytes to megabyte in Java. What I have tried to do is:

        long inodeSpace = 100000;
        long MEGABYTE = 1024L * 1024L;
        long inodeSpaceInMb = inodeSpace / MEGABYTE;
        System.out.println("INODE SPACE " + inodeSpace);
        System.out.println("INODE MB " + inodeSpaceInMb);

I tried to print out the inodeSpaceMb, however, I am getting 0. Any ideas why is it so?

Zoe
  • 27,060
  • 21
  • 118
  • 148
dummygg
  • 233
  • 1
  • 3
  • 12

2 Answers2

2

Cast one of the two into a double and store the result in a double. Like:

double inodeSpaceInMb = (double) inodeSpace / MEGABYTE;
MrMister
  • 2,456
  • 21
  • 31
0

If you also want some precision to a specific decimal place when you do the conversion then you can do this:

 public double bytesToMegabytes(long byteValue, int precision) {
     if (precision < 0) {
         throw new IllegalArgumentException("Precision can not be less than 0!");
     }
     double mbValue = byteValue * 0.000001;
     BigDecimal bigDec = new BigDecimal(mbValue);
     bigDec = bigDec.setScale(precision, RoundingMode.HALF_UP);
     return bigDec.doubleValue();
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22