String.Format(“{0:C2}”, -1234) (Currency format) treats negative numbers as positive

心不动则不痛 提交于 2019-11-30 06:36:09

Am I right in saying it's putting it in brackets, i.e. it's formatting it as ($1,234.00) ? If so, I believe that's the intended behaviour for the US.

However, you can create your own NumberFormatInfo which doesn't behave this way. Take an existing NumberFormatInfo which is "mostly right", call Clone() to make a mutable copy, and then set the CurrencyNegativePattern appropriately (I think you want value 2).

For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        var usCulture = CultureInfo.CreateSpecificCulture("en-US");
        var clonedNumbers = (NumberFormatInfo) usCulture.NumberFormat.Clone();
        clonedNumbers.CurrencyNegativePattern = 2;
        string formatted = string.Format(clonedNumbers, "{0:C2}", -1234);
        Console.WriteLine(formatted);
    }
}

This prints $-1,234.00. If you actually want exactly $-1234, you'll need to set the CurrencyGroupSizes property to new int[]{0} and use "{0:C0}" instead of "{0:C2}" as the format string.

EDIT: Here's a helper method you can use which basically does the same thing:

private static readonly NumberFormatInfo CurrencyFormat = CreateCurrencyFormat();

private static NumberFormatInfo CreateCurrencyFormat()
{
    var usCulture = CultureInfo.CreateSpecificCulture("en-US");
    var clonedNumbers = (NumberFormatInfo) usCulture.NumberFormat.Clone();
    clonedNumbers.CurrencyNegativePattern = 2;
    return clonedNumbers;
}

public static string FormatCurrency(decimal value)
{
    return value.ToString("C2", CurrencyFormat);
}
epotter

Another simple option is manually specify the format string.

String.Format("{0:$#,##0.00}", -1234)

Or, if the currency symbol needs to be a parameter, you could do this

String.Format("{0:" + symbol + "#,##0.00}", -1234)

I think I will simply use:

FormatCurrency(-1234.56, 2, UseParensForNegativeNumbers:=TriState.False)

(in Microsoft.VisualBasic.Strings module)

Or in shorter words (this is what im actually going to use):

FormatCurrency(-1234.56, 2, 0, 0)

Or I will make myself a custom formatcurrency function that uses the VB function passing my custom params.

For further details take a look at the FormatCurrency Function (Visual Basic) in the msdn.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!