【问题标题】:Java Currency Formatter adding parenthesis to the negative valuesJava Currency Formatter 为负值添加括号
【发布时间】:2016-03-15 13:20:43
【问题描述】:

我正在尝试使用 Number Formatter 并且在格式化负值时,它会在其周围附加 ()。

这里是代码

double amount =-200.0;
    Locale locale = new Locale("en", "US");      
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
    System.out.println(currencyFormatter.format(amount));

当我查看格式化程序时,它的负前缀为“($”。这会造成损害。我使用 java.text.NumberFormat 作为数字格式化程序。

是否有任何其他可以使用的格式化程序不会将“()”添加到我的负值中。 ?

【问题讨论】:

标签: java formatting number-formatting


【解决方案1】:

用你的货币格式化程序添加这两行

currencyFormatter.setNegativePrefix("-")
currencyFormatter.setNegativeSuffix("")

【讨论】:

  • 非常感谢。第二行完成了这项工作!
【解决方案2】:

也许在这种情况下最好避免使用货币格式化程序?您可以尝试使用通用十进制格式化程序:

double amount = -200.0;
DecimalFormat formatter = new DecimalFormat("$#,##0.00;$-#,##0.00");
String result = formatter.format(amount);
System.out.println(result);

传递给构造函数的模式可以防止使用括号来表示否定(当然你可以用任何你喜欢的方式改变它)。

【讨论】:

  • 如果你能解释你的答案,而不是仅仅转储一些代码,这会有所帮助。
猜你喜欢
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多