Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

java - Long float-number output shows letters

I have the following code:

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

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

The method fileList[i].length() returns 311 bytes as the type Long.

The previous code results in the following output:

3.88E-4

How do I get my expected output of 0,000311 inside the fileLengthMegabytes variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is Scientific Notation.

AND you are getting 388 instead of 311 because you are dividing by 1000000 instead of 1048576 (1024 * 1024)

EDIT: 311 is not achieved even with 1048576, that way you get 370... so the error is probably in your calc ;)

As described here , you just have to convert your Scientific Notation to a Decimal Notation through a Formatter.

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

Running Example: 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));
        }
}

Output:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...