首页 > 解决方案 > 如何根据区域设置格式化数字,同时保留所有小数点?

问题描述

我正在尝试使用 DecimalFormat 转换双精度值的小数分隔符,同时保留原始数字的所有小数。DecimalFormatter 接受格式为“0.##”的模式,例如。由于我必须使用具有不同小数的数字,因此这将不起作用,因为始终需要在模式中指定小数位数。

我正在寻找一种方法来解决这个问题。

我试过String.format。DecimaFormatter 和 NumberFormatter

理想情况下,我想要的是以下内容:

  private static final ThreadLocal< DecimalFormat > formatter = new ThreadLocal< DecimalFormat >() 
  {
    @Override
    protected DecimalFormat initialValue() 
    {
    // n should be any number of decimals without having to specify them.
      return new DecimalFormat("0.0#n");     
    }
  };

一些例子:

DecimalFormat df = new DecimalFormat("0.0##");
System.out.println(df.format(2.456))
System.out.println(df.format(2.1));

结果:

2,456 -> Good
2,100 -> Not good

我想设置一个模式/正则表达式,它适用于小数点分隔符后任意位数的双精度,例如:

2,456 -> Good
2,1 -> Good
3,3453456345234 -> Good

标签: javaformat

解决方案


Java 中的数字(通常只是数字)没有固定的小数位数。1.1, 1.10, 和1.100都是完全相同的数字。

您可以找出默认格式将使用多少个地方,例如:

String str = num.toString();
int decimal = str.indexOf('.');
int places = decimal <= 0 ? 0 : str.length - decimal;

...然后在使用格式化程序时指定很多地方。


推荐阅读