简体   繁体   中英

How to use the DecimalFormat pattern properly

I have checked this oracle tutorial and it says that this is the pattern syntax:

pattern := subpattern{;subpattern} //where the subpattern between curly braces is for negative numbers;

So I tried the following code, but when I try to format a negative number I actually get back a positive number formatted with the first subpattern.

   NumberFormat nf = NumberFormat.getInstance(Locale.forLanguageTag("us-US-u-ca-buddhist"));
        DecimalFormat dcfCasted = (DecimalFormat)nf;
        dcfCasted.applyPattern("$000,000.000;000.000");
        System.out.println(dcfCasted.format(-200000.100));

I know us-US it's the standard, just wanted to see how it works. Thanks in advance.

As the definition of API ,

the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern.

So make you code like this:

dcfCasted.applyPattern("$000,000.000;-000.000");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM