Is it possible to add a $ to a field using FileHelpers library

829 Views Asked by At

Is it possible to add a $ to a field using FileHelpers library? I have an object

[DelimitedRecord("|")]
public class TradesToBloombergFileHeaders
{
    [FieldOrder(1)]
    public  Guid id;
    [FieldOrder(2)]
    public  string name;
    [FieldOrder(3)]
    public  double price;
    [FieldOrder(4), FieldConverter(ConverterKind.Date, "yyyyMMdd")]
    public  DateTime date;
}

I'm generating a file and want price to be in this format $xxx.xx. Is it even possible? I searched, read documentaion and I don't see anything similar to what i need. Thanks!

4

There are 4 best solutions below

1
On

Probably the attributes:

    [FieldOrder(3), FieldConverter(ConverterKind.Decimal, "C")]
    public decimal price;

will do that for you. As you see I changed the type to decimal which is better for prices/money.

See Standard Numeric Format Strings and ConverterKind enum.


Actually I have never used FileHelpers. The page Arguments for the Default Converters of the library seems to indicate that I cannot use a standard format string like "C" above. If that is the case, try to imitate the example from Decimal Custom Converter instead, perhaps?

0
On

What I did once is make the attribute that will get populated by the text file data private, and create a custom public attribute with accessors

[FieldOrder(3)]
private double _price;

public string price
{
    get { return string.Format("{0}$", _price.ToString()); }
    set { _price = Convert.ToDouble(value.replace('$', '')); }
}

You might want to adjust what the conversion will end up looking like, but you get the idea.

1
On

On output...

Example:

Console.WriteLine("{0}, {1}, {2}, {3}, ${4}", detail.CheckID, detail.IssueDate, detail.StopIndicator, detail.Payee, detail.CheckAmount);
0
On

@Francis's answer below did not work for me, and I didn't see the poster's comment with his answer until later. I thought I would clean it up, and called it out as an answer for others who stumble onto this post, trying to figure out how to format the output.

In my case, I was formatting a string data type so I defined the 'StringToField' method instead, but I've provided the code to address the poster's data type below.

public class MoneyFormatter : ConverterBase
{
    public override object FieldToString(string fieldValue)
    {
        var val = fieldValue == null ? 0 : Convert.ToDecimal(fieldValue); 
        return "$" + val.ToString(CultureInfo.InvariantCulture); 
    }
}

[FieldOrder(3)]
[FieldConverter(typeof(MoneyFormatter))]
public double price;