简体   繁体   中英

Converting String to double in java. Change format of printed double

I am reading a following CSV file in java and

1191196800.681 - !AIVDM,1,1,,,13aG?N0rh20E6sjN1J=9d4<00000,0*1D

Here is my code to read this CSV file and convert the 1st column of the CSV file (which is a String) to a double

public class ReadCSV {

public static void main(String[] args) {

    try {
        BufferedReader CSVFile = new BufferedReader(new FileReader(
                "C:\\example.txt"));

        try {
            String dataRow = CSVFile.readLine();

            while (dataRow != null) {
                String[] dataarray = dataRow.split("-");

                String temp = dataarray[0];

                double i = Double.parseDouble(temp);

                System.out.println(temp);
                System.out.println(i);
                dataRow = CSVFile.readLine();

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

}

When I execute the code I get the following values

1191196800.681 
1.191196800681E9

Why is the value of variable "temp" and "i" not the same. What changes must I do in the code to get the following values:

1191196800.681 
1191196800.681 

Thanks in advance.

temp and i are exactly the same, just the double value is formatted in scientific notation. You can format it differently if you like using DecimalFormat for instance.

Yups vizier is correct what you need to do is this:

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    String dataRow = "1191196800.681";


        String[] dataarray = dataRow.split("-");

        String temp = dataarray[0];
        DecimalFormat df = new DecimalFormat("#.###");
        double i = Double.parseDouble(temp);

        System.out.println(temp);
        System.out.println(df.format(i));

}

The other result is in scientific notation, but is the same.

If you want change the representation you can use String.format("%.3f", i) , which represents the number with 3 decimals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM