如何根据区域设置格式化数字,同时保留所有小数点?

我正在尝试使用DecimalFormat转换double值的Decimal分隔符,同时保留原始数字的所有小数。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


慕的地8271018
浏览 514回答 3
3回答

UYOU

Java中的数字(通常只是数字)没有设定的小数位数。1.1,1.10和1.100,都是完全相同的数字。您可以找出默认格式将使用的位数,例如:String str = num.toString();int decimal = str.indexOf('.');int places = decimal <= 0 ? 0 : str.length - decimal;...然后在使用格式化程序时指定许多位置。

陪伴而非守候

所以你有了double[]&nbsp;floats&nbsp;=&nbsp;{&nbsp;3.20,&nbsp;4.500,&nbsp;6.34,&nbsp;1.0000&nbsp;};BigDecimal[]&nbsp;fixeds&nbsp;=&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;BigDecimal("3.20"), &nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;BigDecimal("4.500"), &nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;BigDecimal("6.34"), &nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;BigDecimal("1.0000")};并希望将它们格式化,但本地化。好消息是BigDecimal的定点数保持精度(使用字符串构造函数)。坏消息是浮点数是近似值,是2的(负)幂的总和。因此3.20实际上可能是3.19999987或3.20000043。它们没有固定的小数。即使没有近似误差3.2 == 3.20 == 3.200。所以转换为BigDecimal(非常难看),并摆脱近似误差:1000 * 3.2!= 3200.0。BigDecimal&nbsp;value&nbsp;=&nbsp;new&nbsp;BigDecimal("5.1000");NumberFormat&nbsp;df&nbsp;=&nbsp;NumberFormat.getInstance(Locale.KOREA); df.setMinimumFractionDigits(value.getScale());&nbsp;//&nbsp;4String&nbsp;s&nbsp;=&nbsp;df.format(value);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java