用减号格式化负数美元,而不是括号 (Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2056400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:05:00  来源:igfitidea点击:

Format negative amount of USD with a minus sign, not brackets (Java)

javacurrencynumber-formatting

提问by ?ygimantas

How do I get NumberFormat.getCurrencyInstance()to print negative USD currency values with a minus sign?

如何NumberFormat.getCurrencyInstance()使用减号打印负美元货币价值?

采纳答案by ?ygimantas

Since I faced this problem again, I did some research and found a more resilient solution provided by an ICU:

由于我再次遇到这个问题,我做了一些研究,发现了一个ICU提供的更具弹性的解决方案:

NumberFormatter
  .withLocale(...)
  .unit(Currency.getInstance("USD"))
  .sign(SignDisplay.AUTO) // "123", "0", and "-123"
  .format(123)
  .toString();

Check API documentation of NumberFormatterfor more details.

查看NumberFormatter 的API 文档以获取更多详细信息。

回答by Michael Borgwardt

It's probably best to create your own DecimalFormatif you want a specific format rather than relying on the default.

DecimalFormat如果您想要特定格式而不是依赖默认格式,最好创建自己的格式。

Edit:You could probably also cast the result of NumberFormat.getCurrencyInstance() to DecimalFormatand adjust it to your preferences.

编辑:您也可以将 NumberFormat.getCurrencyInstance() 的结果转换为DecimalFormat并根据您的偏好进行调整。

回答by Gennadiy

Here is one I always end up using either in a java class or via the fmt:formatNumber jstl tag:

这是我最终在 java 类中或通过 fmt:formatNumber jstl 标签使用的一个:

DecimalFormat format = new DecimalFormat("$#,##0.00;$-#,##0.00");
String formatted = format.format(15.5);

It always produces at least a $0.00 and is consistent when displayed. Also includes thousands seperators where needed. You can move the minus sign in front of the dollar sign if that is your requirement.

它总是至少产生 $0.00 并且在显示时是一致的。在需要时还包括数千个分隔符。如果这是您的要求,您可以在美元符号前面移动减号。

回答by ageektrapped

It requires a little tweaking of the DecimalFormat returned by NumberFormat.getCurrencyInstance()to do it in a locale-independent manner. Here's what I did (tested on Android):

它需要对返回的 DecimalFormat 进行一些调整,NumberFormat.getCurrencyInstance()以独立于语言环境的方式执行此操作。这是我所做的(在Android上测试):

DecimalFormat formatter = (DecimalFormat)NumberFormat.getCurrencyInstance();
String symbol = formatter.getCurrency().getSymbol();
formatter.setNegativePrefix(symbol+"-"); // or "-"+symbol if that's what you need
formatter.setNegativeSuffix("");

IIRC, Currency.getSymbol()may not return a value for all locales for all systems, but it should work for the major ones (and I think it has a reasonable fallback on its own, so you shouldn't have to do anything)

IIRC,Currency.getSymbol()可能不会为所有系统的所有语言环境返回一个值,但它应该适用于主要的语言环境(我认为它本身有一个合理的后备,所以你不应该做任何事情)

回答by E-dou

Try:

尝试:

NumberFormat.getCurrencyInstance(Locale.CANADA);

NumberFormat.getCurrencyInstance(Locale.CANADA);

回答by Pnemonic

NumberFormat.getCurrencyInstance(Locale.UK);

回答by rheaghen

Why poi REFUSES to support the FIRST option in excel currency formatting is beyond me! enter image description here

为什么 poi 拒绝支持 excel 货币格式中的 FIRST 选项是我无法理解的! 在此处输入图片说明

I don't like using the DecimalFormat for currency because your end cell value becomes a non-numeric with the introduction of the currency symbol. While working for a major financial institution, I was tasked with resolving this formatting issue. The core idea of this change is, because POI refuses to be reasonable and have comprehensive support of Excel's native options, I will infiltrate their code and change their values at the core. The following is my WORKAROUND:

我不喜欢使用 DecimalFormat 作为货币,因为随着货币符号的引入,您的最终单元格值变为非数字。在为一家大型金融机构工作时,我的任务是解决这个格式问题。这个改动的核心思想是,因为POI拒绝合理并且对Excel的原生选项有全面的支持,所以我会渗透到他们的代码中,在核心改变他们的值。以下是我的解决方法:

private static final String CURRENCY_FORMAT_OVERRIDE = "\"$\"#,##0.00_);-\"$\"#,##0.00";
private static final String CURRENCY_FORMAT_TARGET = "\"$\"#,##0.00_);(\"$\"#,##0.00)";    

static { // static class level initializer
    Field field = org.apache.poi.ss.usermodel.BuiltinFormats.class.getDeclaredField("_formats");            
    field.setAccessible(true);
    String[] _formats = (String[])field.get(new org.apache.poi.ss.usermodel.BuiltinFormats());
    for(int i = 0; i < _formats.length; ++i) {
        if(_formats[i].equals(CURRENCY_FORMAT_TARGET)) {
            _formats[i]=CURRENCY_FORMAT_OVERRIDE;
            System.out.println("TAKE THAT, POI!!!");
        }
    }
}