English 中文(简体)
Format negative amount of USD with a minus sign, not brackets (Java)
原标题:

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

最佳回答

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

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

Check the API documentation of NumberFormatter for more details.

问题回答

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 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)

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

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.

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

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

Try:

NumberFormat.getCurrencyInstance(Locale.CANADA);

NumberFormat.getCurrencyInstance(Locale.UK);

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

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:

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!!!");
        }
    }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签