我有以下代码:

String curDir = ".";
File fileObject = new File(curDir);
File[] fileList = fileObject.listFiles();

float fileLengthMegabytes = (float)fileList[i].length() / 1000000;

方法fileList [i] .length()返回311个字节,类型为Long。

前面的代码产生以下输出:

3.88E-4

如何在fileLengthMegabytes变量中获得期望的输出0,000311?

最佳答案

那是科学记数法。

并且您得到388而不是311,因为您要除以1000000而不是1048576(1024 * 1024)

编辑:即使1048576也无法实现311,那样您就得到370 ...所以错误可能在您的calc中;)

作为described here,您只需要通过格式化程序将科学计数法转换为十进制计数法。

DecimalFormat df = new DecimalFormat("#.########");
return df.format(fileLengthMegabytes);

运行示例:http://ideone.com/2lkKv7
import java.util.*;
import java.lang.*;
import java.text.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
                DecimalFormat df = new DecimalFormat("#.##########");

        float fileLengthMegabytes1 = (float) 388 / 1000000;
        float fileLengthMegabytes2 = (float) 388 / 1048576;
        System.out.println("MB1 in Scientific Notation: " +
                            fileLengthMegabytes1);
        System.out.println("MB1 in Decimal Notation: " +
                            df.format(fileLengthMegabytes1));
        System.out.println("MB2 in Scientific Notation: " +
                            fileLengthMegabytes2);
        System.out.println("MB2 in Decimal Notation: " +
                            df.format(fileLengthMegabytes2));
        }
}

输出:

09-12 10:38