将负十进制转换为字符串会丢失 -

时间:2010-04-02 20:57:16

标签: c#

我需要发送一个负面的myDecimalValue.ToString(“C”);问题是如果myDecimalValue是负数,让我们说-39,转换后我得到$ 39.00作为字符串不是$ 39.00。所以我不确定该怎么做。

这是采用小数的实用方法。如果小数是负数,我希望ToString显示负数

    public static BasicAmountType CreateBasicAmount(string amount, CurrencyCodeType currencyType)
    {
        BasicAmountType basicAmount = new BasicAmountType
                                          {
                                              currencyID = currencyType,
                                              Value = amount
                                          };
        return basicAmount;
    }

我可以去任何一种方式,一个C或F2,所有我关心的是如果传入的小数是负数,那么在字符串中得到负号。我想除非我在这里查看我的实用程序方法中的否定性,否则没有办法做到这一点。我不能只发送一个负数并期望ToString工作,并且ToSTring会自动看到小数是否为负数?

4 个答案:

答案 0 :(得分:8)

这应该适合你:

decimal num = -39M;
NumberFormatInfo currencyFormat = new CultureInfo(CultureInfo.CurrentCulture.ToString()).NumberFormat;
currencyFormat.CurrencyNegativePattern = 1;
Console.WriteLine(String.Format(currencyFormat, "{0:c}", num));  // -$39.00

答案 1 :(得分:5)

你可以试试这个:

decimal myDecimalValue = -39m;
string s = String.Format("${0:0.00}", myDecimalValue); // $-39.00

但是,SLaks是正确的,负值通常显示在括号中。

答案 2 :(得分:2)

负货币用括号表示,而不是减号:($39.00)

这由您传递给NumberFormatInfo的{​​{1}}的{​​{1}}控制。

答案 3 :(得分:1)

来自"Standard Numeric Format Strings"

  

... InvariantInfo的默认值为0,   代表“($ n)”,其中“$”是   CurrencySymbol和n是一个数字。

所以你可以调用ToString(IFormatProvider)而不是ToString(),传递你设置CurrencyNegativePattern = 1的NumberFormatInfo;

     decimal d = -39M;
     NumberFormatInfo nfi = new NumberFormatInfo();
     nfi.CurrencySymbol = "$"; // didn't default to "$" for me.
     nfi.CurrencyNegativePattern = 1;
     string s = d.ToString("C", nfi); // -$39.00