我需要发送负数 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/