Convert decimal to string with at least a zero for integer value in C#

48 Views Asked by At

I try to figure out how I can convert to strings the values with decimal type of these Account1, Account2, Account3 with at least one zero after the decimal separator for integer values.

Person person = new()
{
    Name = "Tom",
    Account1 = 1m,
    Account2 = 0.2m,
    Account3 = 0.003m
};

var props = person.GetType().GetProperties();
foreach (var prop in props)
{
    var value = prop.GetValue(person);
    if (value?.GetType() == typeof(decimal))
    {
        decimal casted_value = (decimal)value;
        Console.WriteLine(casted_value.ToString("0.0#", CultureInfo.InvariantCulture));
    }
}

class Person
{
    public string? Name { get; set; }
    public decimal Account1 { get; set; }
    public decimal Account2 { get; set; }
    public decimal Account3 { get; set; }
}

Current output:

1.0
0.2
0.0 // Expected: 0.03 => so I should add a "#" to "0.0#" but what if the account value is 0.0004? ... same issue...

Thank you for your help.

0

There are 0 best solutions below