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 overrideDefaultTypeConverter.ConvertToString()
and so the number number style is not used at all when formatting. And, whileDoubleConverter
does overrideConvertToString()
, it doesn't usememberMapData.TypeConverterOptions.NumberStyles
.Both converters do override
ConvertFromString()
and useTypeConverterOptions.NumberStyles
inside, so the number style does indeed get used when reading a CSV file.
Demo fiddle here.