在Java中,DecimalFormat类可用于格式化数字。以下是一些常用的DecimalFormat用法:
DecimalFormat df = new DecimalFormat();
df.applyPattern(“0.00”); // 设置格式为保留两位小数
String formattedNumber = df.format(123.456); // 格式化数字为"123.46"
df.setMinimumFractionDigits(2); // 设置最小小数位数为2
df.setMaximumFractionDigits(4); // 设置最大小数位数为4
df.setGroupingUsed(true); // 使用分组分隔符
df.setDecimalSeparator(‘.’); // 设置小数点分隔符为点号
df.setGroupingSeparator(‘,’); // 设置千位分隔符为逗号
df.setPositivePrefix(“+”); // 设置正数前缀为"+"
df.setNegativePrefix(“-”); // 设置负数前缀为"-"
df.setZeroDigit(‘0’); // 设置零值显示为"0"
df.setRoundingMode(RoundingMode.HALF_UP); // 设置四舍五入舍入模式
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:java DecimalFormat用法