Search code examples
c#filehelpers

Ignore dollar currency sign ($) in decimal field with Filehelpers library


Suppose I have a Filehelpers class like this:

[DelimitedRecord(",")]
public class SomeRecord
{
    public string Field1;
    public decimal Field2;
}

If I try to import a CSV record like this:

hello,$4.00

I get a FileHelpers.ConvertException: "Error Converting '$4.00' to type: 'Decimal'."

How can I make Filehelpers ignore the $ sign?


Solution

  • I think you'd need to write your own converter and use that converter for Field2. This isn't that difficult, all you need to do is create a class that extends ConverterBase. For example:

    public class CurrencyConverter : ConverterBase
    {
        private NumberFormatInfo nfi = new NumberFormatInfo();
    
        public CurrencyConverter()
        {
            nfi.NegativeSign = "-";
            nfi.NumberDecimalSeparator = ".";
            nfi.NumberGroupSeparator = ",";
            nfi.CurrencySymbol = "$";
        }
    
        public override object StringToField(string from)
        {
            return decimal.Parse(from, NumberStyles.Currency, nfi);
        }
    }
    

    You can then use that converter on your Field2 property:

    [DelimitedRecord(",")]
    public class SomeRecord
    {
        public string Field1;
        [FieldConverter(typeof(CurrencyConverter))]
        public decimal Field2;
    }
    

    and the $4.00 will be parsed as 4.00.

    Obivously my code above isn't that robust. You may prefer to use TryParse rather than just Parse and return 0 if it fails but you get the idea.