简体   繁体   English

在Java中将String转换为double。 更改印刷双打的格式

[英]Converting String to double in java. Change format of printed double

I am reading a following CSV file in java and 我正在用Java阅读以下CSV文件,

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 这是我的代码,用于读取此CSV文件并将CSV文件的第一列(是字符串)转换为双精度

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. 为什么变量“ temp”和“ i”的值不相同。 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. temp和i完全相同,只是double值以科学计数法格式设置。 You can format it differently if you like using DecimalFormat for instance. 例如,如果您喜欢使用DecimalFormat ,则可以设置不同的格式。

Yups vizier is correct what you need to do is this: Yups vizier是正确的,您需要做的是:

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 如果要更改表示形式,则可以使用String.format("%.3f", i) ,该数字表示3位小数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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