Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将十进制(0.5的倍数)设置为整数或混合数的字符串格式?_C#_String_Decimal_String Formatting_Fractions - Fatal编程技术网

C# 如何将十进制(0.5的倍数)设置为整数或混合数的字符串格式?

C# 如何将十进制(0.5的倍数)设置为整数或混合数的字符串格式?,c#,string,decimal,string-formatting,fractions,C#,String,Decimal,String Formatting,Fractions,如何将十进制(始终为0.5的倍数)设置为整数或混合数的字符串格式 示例: 0.00 .... "" or "0" 0.50 .... "1/2" 1.00 .... "1" 1.50 .... "1 1/2" 等等 编辑: 这可能就是我要找的。但我还没试过。我想这类事情有一个正则表达式 public static string ToMixedNumber(this decimal d) { if (d == null || d == 0) return "";

如何将十进制(始终为0.5的倍数)设置为整数或混合数的字符串格式

示例:

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

编辑:
这可能就是我要找的。但我还没试过。我想这类事情有一个正则表达式

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

无法使用默认的格式化程序。您必须实现并编写自己的代码,以从小数部分创建适当的分数。

以下是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));

这就是我最后用的

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

你必须写:
stringnumberasfraction(decimald)
Wy你想这样做吗?这很难,因为你迫使我们放弃一个非常狭隘的假设,即一直是.50的倍数,我有你想要的代码,但它让我觉得里面很脏…@JamesMichaelHare-这也难怪,呃……程序员总是谈论内心肮脏的感觉。这有点令人毛骨悚然!哇,这对我来说太不可思议了!但非常感谢您提供了一个可能有用的答案。我实现了一个IMUSTAVEASKEDTHEQUESTIONE错误的界面,但谢谢您!