简体   繁体   English

如何使用模式将DecimalFormat的分组分隔符(千位)从逗号/点更改为引用?

[英]How to change the grouping separator (thousands) of DecimalFormat from comma/point to quote using patterns?

I have this piece of code where I try to replace the thousands separator (.) for quote (') with this pattern: ###'###,## 我有这段代码,我尝试使用以下模式将引号(')的千位分隔符(。)替换为: ###'###,##

import java.text.*;

  public class NumberFormatTests
  {
    public static void main (String[] args)
    {
      double amount = 100100.543;
      NumberFormat nf = new DecimalFormat("###'###.##");
      System.out.println( "amount with    formatting: " + nf.format(amount) );
    }
  }

but I get this error: 但是我得到这个错误:

Exception in thread "main" java.lang.IllegalArgumentException: Malformed pattern "###'###.##" at java.text.DecimalFormat.applyPattern(DecimalFormat.java:3411) at java.text.DecimalFormat.(DecimalFormat.java:436) at NumberFormatTests.main(NumberFormatTests.java:8) 线程“主”中的异常java.lang.IllegalArgumentException:java.text.DecimalFormat.applyPattern(DecimalFormat.java:3411)处格式错误的模式“ ###'###。##”在java.text.DecimalFormat。(DecimalFormat) .java:436),位于NumberFormatTests.main(NumberFormatTests.java:8)

I know it can be changed programatically by using DecimalFormatSymbols like this: 我知道可以使用DecimalFormatSymbols这样编程地更改它:

import java.text.*;
import java.util.Locale;

  public class NumberFormatTests
  {
    public static void main (String[] args)
    {
      double amount = 100100.543;

      Locale currentLocale = new Locale("de", "DE");
      DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
      unusualSymbols.setGroupingSeparator('\'');

      NumberFormat nf = new DecimalFormat("###,###.##", unusualSymbols);
      System.out.println( "amount with    formatting: " + nf.format(amount) );
    }
  }

but I need to find a way to do it within the pattern, something like "###'###.##". 但是我需要找到一种在模式内完成此操作的方法,例如“ ###'###。##”。 I already tried "###''###.##" but the quote is added as suffix. 我已经尝试过“ ###” ###。##”,但引用已添加为后缀。

Is there any way to replace the thousands separator already within the pattern and not programatically? 有什么方法可以替换模式中已经存在的千位分隔符,而不能以编程方式替换吗?

Can you use a subclass of DecimalFormat instead? 您可以改用DecimalFormat的子类吗? You could analyze the pattern in the subclass and extract the unusual grouping separator from the pattern. 您可以分析子类中的模式,并从模式中提取异常的分组分隔符。 On a call of the subclass's format method, you can use this grouping separator with the original DecimalFormat as shown in your own example code. 在调用子类的format方法时,可以将此分组分隔符与原始DecimalFormat一起使用,如您自己的示例代码所示。 This is the result that is returned by the format method of the subclass. 这是子类的format方法返回的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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