开发者

Converting Negative Decimal To String Loses the -

开发者 https://www.devze.com 2022-12-25 06:22 出处:网络
I\'m required to send in a negative myDecimalValue.ToString(\"C\");The problem is if myDecimalValue is a negative, lets say -39, after conversion I\'m getting $39.00 as the string not $39.00.So I\'m n

I'm required to send in a negative myDecimalValue.ToString("C"); The problem is if myDecimalValue is a negative, lets say -39, after conversion I'm getting $39.00 as the string not $39.00. So I'm not sure how to go about this.

This is the utility method that takes in the decimal. If the decimal is negative, I want the ToString to show a negative

    public static BasicAmountType CreateBasicAmount(string amount, CurrencyCodeType currencyType)
    {
        BasicAmountType basicAmount = new BasicAmountType
                                          {
                                              currencyID = currencyType,
                                          开发者_高级运维    Value = amount
                                          };
        return basicAmount;
    }

I could go either way, a C or F2, all I care is about getting that negative sign intothe string if the incoming decimal is negative. I suppose there's no way to do this unless I check for negativity inside my utility method here. I can't just send a negative number and expect the ToString to work and for the ToSTring to automatically see that the decimal is negative incoming?


This should work for you:

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


You could try this:

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

However, SLaks is right, negative values are usually shown in parenthesis.


Negative currencies are represented by parentheses, not minus signs: ($39.00).

This is controlled by the NumberFormatInfo of the CultureInfo that you pass to ToString.


From "Standard Numeric Format Strings":

...The default for InvariantInfo is 0, which represents "($n)", where "$" is the CurrencySymbol and n is a number.

So you can call ToString(IFormatProvider) instead of ToString(), passing a NumberFormatInfo on which you set CurrencyNegativePattern = 1;

     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
0

精彩评论

暂无评论...
验证码 换一张
取 消