Search code examples
c#stringdecimalstring-formattingfractions

How can I string format a decimal (multiple of 0.5) as a whole or mixed number?


How can I string format a decimal (always a multiple of 0.5) as a whole or mixed number.

examples:

0.00 .... "" or "0"  
0.50 .... "1/2"  
1.00 .... "1"  
1.50 .... "1 1/2"  

and so on..

EDIT:
This might be what I was looking for. But I haven't tried it yet. I imagine there is a Regex for this kind of thing.

public static string ToMixedNumber(this decimal d)
{
    if (d == null || d == 0) return "";
    var s = d.ToString().TrimEnd('0');
    if(s.EndsWith(".")) return s.TrimEnd('.');
    return s.TrimEnd('.') + " 1/2";
}

Solution

  • This is what I ended up using,

    public static string ToMixedNumber(this decimal d)
    {
        if (d == 0) return "";
        var s = d.ToString().TrimEnd('0');
        if (s.EndsWith(".")) return s.TrimEnd('.');
        return s.Split('.')[0] + " 1/2";
    }