java - 如何根据区域设置格式化数字,同时保留所有小数点?
问题描述
我正在尝试使用 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
解决方案
Java 中的数字(通常只是数字)没有固定的小数位数。1.1
, 1.10
, 和1.100
都是完全相同的数字。
您可以找出默认格式将使用多少个地方,例如:
String str = num.toString();
int decimal = str.indexOf('.');
int places = decimal <= 0 ? 0 : str.length - decimal;
...然后在使用格式化程序时指定很多地方。
推荐阅读
- java - Javafx右键编辑listView项及类似方法
- angular - Angular 6 包模块内依赖
- sql - SQL Server 选择所有不具有前缀重复值的记录
- wordpress - 从 Jetpack 的“热门帖子和页面”小部件中排除页面
- angularjs - 在Angularjs中进行下拉输入
- html - 如何使固定覆盖容器中的弹出窗口可滚动?
- solr - 是否可以通过 solrconfig.xml 配置多个 Solr 内核?
- css - CSS 选择器 - DOM 中的第一个匹配项
- python - Python - 列表理解中的 append() 操作导致内存气球
- spring-boot - Spring Boot 中的 SSL 配置和 Apache 服务器中的 SSL 配置