C# String.Format("{0:C2}", -1234)(货币格式)将负数视为正数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1001114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:15:07  来源:igfitidea点击:

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

c#vb.netstring-formattingcurrencystring.format

提问by Shimmy Weitzhandler

I am using String.Format("{0:C2}", -1234)to format numbers.

我正在使用String.Format("{0:C2}", -1234)格式化数字。

It always formats the amount to a positive number, while I want it to become $ -1234

它总是将金额格式化为正数,而我希望它变成 $ -1234

采纳答案by Shimmy Weitzhandler

I think I will simply use:

我想我会简单地使用:

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

(in Microsoft.VisualBasic.Strings module)

(在 Microsoft.VisualBasic.Strings 模块中)

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.

或者我将使自己成为一个自定义格式货币函数,该函数使用传递我的自定义参数的 VB 函数。

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

有关更多详细信息,请查看msdn中的FormatCurrency 函数 (Visual Basic)

回答by Jon Skeet

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.

我说它把它放在括号里是对的,即将它格式化为($1,234.00)?如果是这样,我相信这就是美国的预期行为。

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

但是,您可以创建自己的NumberFormatInfo不以这种方式运行的。取一个NumberFormatInfo“基本正确”的现有文件,调用Clone()创建一个可变副本,然后CurrencyNegativePattern适当地设置(我认为您想要值 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 CurrencyGroupSizesproperty to new int[]{0}and use "{0:C0}"instead of "{0:C2}"as the format string.

这将打印 $-1,234.00。如果您确实想要 $-1234,则需要将该CurrencyGroupSizes属性设置为new int[]{0}并使用"{0:C0}"而不是"{0:C2}"作为格式字符串。

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

回答by 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)

回答by Pawan Kumar Prajapati

#region Format value to currency
    /// <summary>
    /// Method to format input in currency format
    ///  Input:  -12345.55
    ///  Output:$-12,345.55  
    /// </summary>
    /// <param name="Input"></param>
    /// <returns></returns>
    public static string FormatToCurrency(string Input)
    {
        try
        {
            decimal value = Convert.ToDecimal(Input);
            CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
            culture.NumberFormat.NumberNegativePattern = 2;
            return string.Format(culture, "{0:C}", value);
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }
    #endregion