Java中DecimalFormat格式化后去除E0指数形式的方法
如何让DecimalFormat指数格式化时,整数显示普通格式而非指数形式?
先看原代码及输出:
原代码:
import java.math.RoundingMode; public class DecimalFormat { public static void main(String[] args) { java.text.DecimalFormat df = new java.text.DecimalFormat("#.######E0"); df.setRoundingMode(RoundingMode.CEILING); System.out.println(df.format(3)); System.out.println(df.format(19.346346436)); } }
执行输出:
3E0 1.934635E1
需求是:让3的输出变为3,同时保留19.346346436的指数格式输出1.934635E1。
解决方案一:自定义判断逻辑
可以通过判断格式化后的结果是否为指数为0的整数,选择不同的格式器输出:
import java.math.RoundingMode; import java.text.DecimalFormat; public class DecimalFormatTest { public static void main(String[] args) { // 定义指数格式器 DecimalFormat exponentialFormat = new DecimalFormat("#.######E0"); exponentialFormat.setRoundingMode(RoundingMode.CEILING); // 定义普通整数格式器 DecimalFormat plainIntegerFormat = new DecimalFormat("#"); // 测试目标数值 formatAndPrint(3, exponentialFormat, plainIntegerFormat); formatAndPrint(19.346346436, exponentialFormat, plainIntegerFormat); // 测试边界值 formatAndPrint(9.999999, exponentialFormat, plainIntegerFormat); formatAndPrint(10.0, exponentialFormat, plainIntegerFormat); formatAndPrint(0.5, exponentialFormat, plainIntegerFormat); } private static void formatAndPrint(Number num, DecimalFormat expFormat, DecimalFormat plainFormat) { String expResult = expFormat.format(num); // 检查是否是指数为0的情况 if (expResult.endsWith("E0")) { String numericPart = expResult.substring(0, expResult.indexOf('E')); // 判断数值部分是否为整数(无小数点或小数点后全为0) if (!numericPart.contains(".") || numericPart.split("\\.")[1].matches("0+")) { System.out.println(plainFormat.format(num)); return; } } // 不符合条件则输出指数格式 System.out.println(expResult); } }
逻辑说明:
- 先通过指数格式器生成结果
- 如果结果以
E0结尾,提取前面的数值部分 - 验证数值部分是否为整数,若是则用普通整数格式输出,否则仍保留指数格式
解决方案二:使用ChoiceFormat指定范围格式
如果需求是固定范围的数值(比如1到10之间的整数用普通格式,其他用指数格式),可以用ChoiceFormat绑定范围与格式:
import java.math.RoundingMode; import java.text.ChoiceFormat; import java.text.DecimalFormat; import java.text.NumberFormat; public class DecimalFormatChoice { public static void main(String[] args) { // 定义范围边界:0-1、1-10、10以上 double[] rangeLimits = {0, 1, 10}; // 对应范围的格式器 NumberFormat[] formatters = { getExponentialFormat(), new DecimalFormat("#"), getExponentialFormat() }; // 创建ChoiceFormat绑定范围与格式器 ChoiceFormat formatSelector = new ChoiceFormat(rangeLimits, formatters); // 测试输出 System.out.println(formatSelector.format(3)); System.out.println(formatSelector.format(19.346346436)); System.out.println(formatSelector.format(9.999999)); System.out.println(formatSelector.format(0.5)); } private static DecimalFormat getExponentialFormat() { DecimalFormat df = new DecimalFormat("#.######E0"); df.setRoundingMode(RoundingMode.CEILING); return df; } }
这个方法更简洁,直接通过范围匹配选择对应的格式器,适合规则明确的场景。
内容的提问来源于stack exchange,提问作者Infinity Plus One
相关产品推荐
相关产品推荐

