Search code examples
supercsv

Parsing double superCSV with comma as decimal separator?


I Want to parse a double with comma as decimal separator (',' instead of '.') using SuperCSV CellProcessor

I want to parse the first element (0,35) to Double

0,35;40000,45 

I have tried something like that :

   /** FRENCH_SYMBOLS */
private static final DecimalFormatSymbols FRENCH_SYMBOLS = new DecimalFormatSymbols(Locale.FRANCE);
  DecimalFormat   df =   new DecimalFormat();
  df.setDecimalFormatSymbols(FRENCH_SYMBOLS);
 final CellProcessor[] processors = new CellProcessor[] {
                new NotNull(new ParseDouble(new FmtNumber(df))),
                new NotNull(new ParseBigDecimal(FRENCH_SYMBOLS)) };

ParseBigDecimal works just fine but the parseDouble doesn't seems to work, it gives me an exception : org.supercsv.exception.SuperCsvCellProcessorException: '0,35' could not be parsed as a Double


Solution

  • You're totally correct - ParseDouble doesn't support a French-style decimal separator (comma), but ParseBigDecimal does. If you think this is a useful feature, why not submit a feature request.

    The simplest workaround is to simply chain a StrReplace before the ParseDouble to convert the comma to full stop.

    new StrReplace(",", ".", new ParseDouble())
    

    Alternatively, you could write a custom cell processor that either:

    • parses a Double (with a configurable decimal separator)

    • converts a BigDecimal to a Double (calling doubleValue()) - this can then be chained after your new ParseBigDecimal(FRENCH_SYMBOLS)

    Oh, and in future you might want to mention that your file is semi-colon separated and you've set up Super CSV with CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE :)