Search code examples
javacsvapache-commonsopencsvapache-commons-csv

Apache commons CSVPrinter is encoding Double values


I am trying to read some data from a list and writing that into a csv file without any formatting or encoding. Just comma separated values

but the problem is, when I am writing any value such as 0.0000666, it encoded to 6.66E-5. I want no formatting. My desired output is 0.0000666 should be written as 0.0000666 only.

// getting a list in input

    try (BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(fileName));
                CSVPrinter csvPrinter = CSVFormat.DEFAULT
                        .withEscape(Character.MIN_VALUE)
                        .withQuoteMode(QuoteMode.NONE)
                        .withHeader(HEADERS)
                        .withIgnoreHeaderCase()
                        .withTrim()
                        .print(bufferedWriter);) {
            
            csvPrinter.printRecords(list);

            bufferedWriter.flush();
            bufferedWriter.close();
            csvPrinter.close();

        } 

Solution

  • So I figured it out what in real was the problem.

    Double encodes itself into scientific donations if the value < 1. So whenever I was printing some smaller value like 0.0000666 in csv the CSVPrinter was writing it as 6.66E-5.

    I formatted the value before writing it to csv and wrote the formatted values. Someting like this.

    String.format("%.4f", 6.66E-5)