TurtleFan
TurtleFan

Reputation: 289

Formatting a float to string at constructor level

I have a constructor that builds a table. The way the data is fed in is quite complex and depends on previous data. One of my columns displays a float that I would like to format as currency. I want to do this at the level where it is get and set, so when I get or set the data I'm working with a float, but when it's displayed it's a formatted string. I have the methods to convert into and convert back into the desired format. How can I implement them?

Example Code

public class WarehouseItem
{
    public WarehouseItem(int id, int parentID, string clientID, string instrumentID, string orderID, string status, float openPosition, float execPosition, float cumOpenPosition, float cumExecPosition, string time, string logTime)
    {    
        this.OpenPosition = openPosition;
    }

    public float OpenPosition
    {
        get; // returns float (retroConvert)
        set; // takes a float -> string (convert)
    }

    private float retroConvert(string input)
    {
        string str = input.Replace(",", "");
        return float.Parse(str);
    }

    private string convert(float input)
    {
        return ((float)input).ToString("#,##0.00");
    }  
}

Upvotes: 2

Views: 184

Answers (1)

Steve
Steve

Reputation: 9583

You could use another field that only has a getter to return the formatted string.

Eg.

public string OpenPositionFormatted
{
    get { return convert(OpenPosition); }
}

Upvotes: 4

Related Questions