C#culture info /为货币设置特定的tostring

时间:2012-05-02 14:15:01

标签: c# tostring cultureinfo

我希望制作一个客户十进制格式。我现在得到的是#34;(3003.3003d).ToString(#,###。00 ##")是" 3,003.3003"。我想要的格式是" 3' 003.300,3"。

我可以使用客户方法math.floor并自行分解,但我很好奇是否有办法使用文化信息来做我想要的事情。有人知道这样做的方法吗?

用定制的IFormatprovider写这个家伙作为答案,因为教程非常好,但我不相信当前的文化存在于我需要的东西。这是我的最终答案:

private string ToCustomDecimal(decimal Input, int MaxLenPostDec, int MinLenPostDec)
    {
        string CustD;
        string[] Split = Input.ToString().Split('.');
        string BigNum = Split[0];
        string SmallNum = "0";
        if (Split.Length > 1)
            SmallNum = Split[1];
        int Spot = 0;
        bool FirstD = false;
        string OutBigNum = "";
        for (int Locc = BigNum.Length - 1; Locc >= 0; Locc--)
        {
            Spot++;
            if (FirstD == false)
            {
                OutBigNum = BigNum.Substring(Locc, 1) + OutBigNum;
                FirstD = true;
            }
            else
                OutBigNum = (Spot % 3 == 1 ? "'" : "") + BigNum.Substring(Locc, 1) + OutBigNum;
        }
        Spot = 0;
        FirstD = false;
        string OutSmallNum = "";
        for (int Locc = 0; Locc < SmallNum.Length; Locc++)
        {
            Spot++;
            if (FirstD == false)
            {
                OutSmallNum += SmallNum.Substring(Locc, 1);
                FirstD = true;
            }
            else
            {
                OutSmallNum += (Spot % 3 == 1 ? "," : "") + SmallNum.Substring(Locc, 1);
            }
            if (Locc >= MaxLenPostDec - 1)
                break;
            if (Locc == SmallNum.Length - 1 && MinLenPostDec > Locc)
            {
                for (int Locc2 = Locc; Locc2 < MinLenPostDec - 1; Locc2++)
                {
                    Spot++;
                    OutSmallNum += (Spot % 3 == 1 ? "," : "") + 0;
                }
            }
        }
        CustD = OutBigNum + "." + OutSmallNum;
        return CustD;
    }

3 个答案:

答案 0 :(得分:3)

您应该查看重载ToString("#,###.00##", myFormatProvider)

所以你需要一个custom IFormatprovider

答案 1 :(得分:1)

这似乎可行,但我没有测试它。

(3003.3003d).ToString(@"#\'###.00#\,##")

答案 2 :(得分:0)

使用IFromatProvider查看Decimal.ToString重载。我想你要么想用特定的(CultureInfo.CreateSpecificCulture())或当前的文化(CultureInfo.CurrentCulture)来显示用户货币。