Apache commons CSVPrinter is encoding Double values

554 Views Asked by At

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();

        } 
2

There are 2 best solutions below

0
Akif On BEST ANSWER

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)
0
somayaj On

defining the value as a string will work here. ex:

 printer.printRecord(1, "john73", "John", "Doe", "0.0000666");

vs

 printer.printRecord(1, "john73", "John", "Doe", 0.0000666);