c# - 将负小数转换为字符串会丢失 -

标签 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 自动看到小数是负数传入吗?

最佳答案

这应该适合你:

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

关于c# - 将负小数转换为字符串会丢失 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2569166/

相关文章:

c# - 如何监控 Active Directory 用户登录/注销?

c# - 如何抑制 stylecop 错误 SA1650(拼写错误的单词)

c# - Visual Studio 中的 .NET Core 应用程序独立发布

c# - 限制事件队列的最佳实践

c# - 创建用于 C# 程序的 CPP DLL

c# - ListView.RetrieveVirtualItem 事件到底是什么 - C#

C# Executable 执行目录

c# - Asp.net 和 C# 错误 : The name "mygv" does not exist in the current context

c# - 在 Windows 7 中使用 VC++ 和 C# 中的 MemoryMappedFiles 或命名管道进行进程间通信

c# - C# 上 64 位架构上的 SetupDiEnumDeviceInterfaces