【问题标题】:Using CultureInfo in order to replace USD symbol with -使用 CultureInfo 将美元符号替换为 -
【发布时间】:2019-10-02 09:02:31
【问题描述】:

我目前正在使用此代码删除 US symbol 并使数字显示为否定

我使用的代码是:

public strNegative = "-";

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

但是结果显示带括号:

结果 = "(-5)"

当需要的格式是

结果 = "-5"

【问题讨论】:

  • 格式字符串“C3”要求字符串格式函数将值显示为货币。如果您不想要 $ 符号,为什么要使用它?另外,您为什么要混合符号指示符和货币符号?
  • 因为我需要数字显示为 -5.000 。我正在使用它,因为我正在处理不同的货币。
  • 如果您想要 3 位小数而不需要货币单位,只需使用 ToString("N3")。
  • 这与货币有什么关系?数字 -5 可以使用 TrnAmount.ToString("0.000") 显示为“-5.000”,与货币无关
  • 克隆 NumberFormatInfo 并调整货币属性(如果这确实是货币)

标签: c# cultureinfo


【解决方案1】:

欢迎。要获得负数,只需将数字乘以 -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

【讨论】:

    【解决方案2】:

    从技术上讲,您可以创建自己的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2021-07-13
      • 2013-01-11
      • 2016-02-13
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多