使用CultureInfo将美元符号替换为-

问题描述 投票:0回答:2

我当前正在使用此代码来删除 US symbol,并使数字显示为负数

我正在使用的代码是:

public strNegative = "-";

string Result = TrnAmount
  .ToString("C3", new CultureInfo("en-US"))
  .Replace("$", strNegative);

但是结果显示为带有括号

结果= "(-5)"

当需要的格式是

结果= "-5"

c# cultureinfo
2个回答
4
投票

欢迎。要获得负数,只需将数字乘以-1。如果要获取通用编号而不是货币格式,请使用N3 as a string format

float TrnAmount = 2.5684155f;
string result = (-1 * TrnAmount).ToString("N3");
Console.WriteLine(result); //This will give you -2.568 as a result

1
投票

从技术上讲,您可以创建自己的CultureInfo,例如

  // Same as US
  CultureInfo myUSCulture = new CultureInfo("en-US", true);

  // Except dollar sign removed
  myUSCulture.NumberFormat.CurrencySymbol = "";
  // and negative pattern changed: "-value" instead of "(value)"
  myUSCulture.NumberFormat.CurrencyNegativePattern = 1;

然后使用它:

  decimal TrnAmount = -123456789.987M;

  Console.WriteLine(TrnAmount.ToString("C3", myUSCulture)); // exactly 3 digits after .
  Console.WriteLine(TrnAmount.ToString("C2", myUSCulture)); 
  Console.WriteLine(TrnAmount.ToString("C0", myUSCulture)); // no floating point

结果:

  -123,456,789.987
  -123,456,789.99  // rounded
  -123,456,790     // rounded
© www.soinside.com 2019 - 2024. All rights reserved.