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

Suppose I have a Filehelpers class:

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

      

If I try to import a CSV record like:

hello,$4.00

      

I get FileHelpers.ConvertException

: "Convert errors" $ 4.00 "for input:" Decimal ".

How do I make Filehelpers ignore the $ sign?

+3


source to share


1 answer


I think you need to write your own converter and use this converter for Field2

. It's not that hard, all you have 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);
    }
}

      

Then you can use this converter on the property Field2

:



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

      

and $ 4.00 will be parsed as 4.00.

Abundantly my code above is not that solid. You may prefer to use TryParse

rather than just Parse

return 0

if it fails, but you get the idea.

+5


source







All Articles