Search code examples
c#asp.net-mvcstring-formatting

How would I format a string value from a custom list into money format?


I know this is likely a duplicate question and for that I am sorry. I have been looking for a way to format a custom string, that is pulling values from SQL database. I have read many S.O. on formatting and none have worked.

Ideally I would want the string value to come out something close to $999,888,432.23 (this value is only a placeholder).

Below is one of the ways I have tried to get this string value formatted and I just don't understand why there was 0 changes.

The current string value output is something like 5921.1500000000 (for example; there are always 5-10 trailing 0 that I am trying to remove).

Please let me know if you need more information.

for (int i = 0; i < Sort_List.Count; i++)
{
    Sort_List[i].DollarsOpen = string.Format("{0:0.00}", Sort_List[i].DollarsOpen);
}

Update 1: The following is all the converted data types that is coming from the database. Originally DollarsOpen was a decimal

public class JTPosOpen
{
    public string PoDate;
    public string VendorNo;
    public string Vendor;
    public string PONumber;
    public string POLine;
    public string QtyOrdered;
    public string QtyReceived;
    public string QtyRemaining;
    public string UOM;
    public string ExpUnitCost;
    public string DollarsOpen;
    public string GLAcct;
    public string GLCtr;
    public string JobNo;
    public string ItemNo;
    public string Desc1;
    public string Desc2;
    public string RequestDate;
}

Solution

  • The better data type to save currency is decimal.

    Therefore, keep data as decimal and when it is necessary convert it to the string:

    decimal price = 123456.4444m;
    Sort_List[i].DollarsOpen = $"{price:C}";
    

    The formatted value here will be "$123,456.44".


    Perhaps you will need to specify the `CultureInfo` if the current culture in your environment uses the currency symbol different from the `$`:
    Sort_List[i].DollarsOpen = price.ToString("C", new System.Globalization.CultureInfo("en-US"));