我有以下代码:
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)
编辑:311即使使用1048576也没有实现,这样你就可以得到370 …所以错误可能在你的calc中);
作为described here,您只需要通过格式化器将您的科学符号转换为十进制符号.
DecimalFormat df = new DecimalFormat("#.########"); return df.format(fileLengthMegabytes);
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)); } }
输出:
MB1 in Scientific Notation: 3.88E-4
MB1 in Decimal Notation: 0.000388
MB2 in Scientific Notation: 3.7002563E-4
MB2 in Decimal Notation: 0.0003700256