Home > OS >  How to use CsvHelper TypeConverter to Format to two decimals?
How to use CsvHelper TypeConverter to Format to two decimals?

Time:01-02

I am using CsvHelper for export, and I'd like to have the text of numbers with two decimals in the output.

I've read the pages on CsvHelper, including Typeconverters but I can't find an example of what I think is pretty simple, and Typeconvers I tried:

Map(m => m.DonationAmount).TypeConverterOption.NumberStyles(NumberStyles.Currency);

But that didn't seem to have any effect.

I also tried

Map(m => m.DonationAmount.ToString("0.00"));

which just errored right out.

I imagine its something simple that I'm missing.

(If it matters, I'm only writing, not reading CSVs with these maps.)

CodePudding user response:

You can use

Map(m => m.DonationAmount).TypeConverterOption.Format("0.00");

TypeConverterOption.Format sets:

The string format to be used when type converting.

Notes:

  • TypeConverterOption.NumberStyles does not work because, as of the most recent version (30.0.1), DecimalConverter does not override DefaultTypeConverter.ConvertToString() and so the number number style is not used at all when formatting. And, while DoubleConverter does override ConvertToString(), it doesn't use memberMapData.TypeConverterOptions.NumberStyles.

    Both converters do override ConvertFromString() and use TypeConverterOptions.NumberStyles inside, so the number style does indeed get used when reading a CSV file.

Demo fiddle here.

  • Related