我正在尝试使用 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