Как я могу отформатировать десятичное число (кратное 0,5) как целое или смешанное число? - PullRequest
1 голос
/ 13 марта 2012

Как я могу отформатировать десятичное число (всегда кратное 0,5) как целое или смешанное число.

Примеры:

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

и т. Д.

EDIT:
Это может быть то, что я искал. Но я еще не пробовал. Я полагаю, что для такого рода вещей есть Regex.

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";
}

Ответы [ 3 ]

2 голосов
/ 13 марта 2012

Вы не можете использовать форматеры по умолчанию.Вам нужно будет реализовать Интерфейс ICustomFormatter и написать собственный код для создания соответствующих дробей из десятичной части.

0 голосов
/ 18 марта 2012

Это то, что я в итоге использовал,

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";
}
0 голосов
/ 13 марта 2012

Вот реализация, предложенная JamieSee:

using System;
using System.Globalization;

class FractionFormatter :ICustomFormatter, IFormatProvider
{
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        // Provide default formatting for unsupported argument types.
        if (!(arg is decimal))
        {
            HandleOtherFormats(format, arg);
        }

        // Provide default formatting for unsupported format strings.
        string ufmt = format.ToUpper(CultureInfo.InvariantCulture);
        if (ufmt != "H")
        {
            try
            {
                return HandleOtherFormats(format, arg);
            }
            catch (FormatException e)
            {
                throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
            }
        }

        decimal value = (decimal)arg;
        int wholeNumber = (int)Math.Floor(value);
        decimal fraction = value - (decimal)wholeNumber;

        if (fraction == 0m)
        {
            return wholeNumber.ToString();
        }
        else if (fraction == 0.5m)
        {
            if (wholeNumber == 0)
            {
                return "1/2";
            }
            else
            {
                return wholeNumber.ToString() + " 1/2";
            }
        }
        else
        {
            throw new ArgumentOutOfRangeException("arg", "Value must be a multiple of 0.5");
        }

    }

    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    private string HandleOtherFormats(string format, object arg)
    {
        if (arg is IFormattable)
            return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
        else if (arg != null)
            return arg.ToString();
        else
            return String.Empty;
    }
}

И вот пример ее использования:

Console.WriteLine(string.Format(new FractionFormatter(), "{0:H}", value));
...