我正在尝试使用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 -> Good2,100 -> Not good我想设置一个模式/正则表达式,它将适用于小数点分隔符之后的任意位数的双精度数:2,456 -> Good2,1 -> Good3,3453456345234 -> Good
3 回答

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

陪伴而非守候
TA贡献1757条经验 获得超8个赞
所以你有了
double[] floats = { 3.20, 4.500, 6.34, 1.0000 };BigDecimal[] fixeds = { new BigDecimal("3.20"), new BigDecimal("4.500"), new BigDecimal("6.34"), new BigDecimal("1.0000")};
并希望将它们格式化,但本地化。
好消息是BigDecimal的定点数保持精度(使用字符串构造函数)。坏消息是浮点数是近似值,是2的(负)幂的总和。因此3.20实际上可能是3.19999987或3.20000043。
它们没有固定的小数。即使没有近似误差3.2 == 3.20 == 3.200。
所以转换为BigDecimal(非常难看),并摆脱近似误差:1000 * 3.2!= 3200.0。
BigDecimal value = new BigDecimal("5.1000");NumberFormat df = NumberFormat.getInstance(Locale.KOREA); df.setMinimumFractionDigits(value.getScale()); // 4String s = df.format(value);
添加回答
举报
0/150
提交
取消