java中如何输出小数
格式化输出小数
使用 System.out.printf 或 String.format 控制小数位数:
double num = 3.1415926;
System.out.printf("%.2f", num); // 输出 3.14
String formatted = String.format("%.3f", num); // 结果为 "3.142"
%.nf 中的 n 指定保留的小数位数,默认四舍五入。
使用 DecimalFormat 类
通过 DecimalFormat 自定义格式:
import java.text.DecimalFormat;
double value = 123.456789;
DecimalFormat df = new DecimalFormat("#.##"); // 保留两位小数
System.out.println(df.format(value)); // 输出 123.46
支持模式如 #.###(可选小数位)、0.000(强制补零)。
直接输出 double 或 float
直接打印变量会显示完整小数位:
double d = 2.71828;
float f = 1.414f;
System.out.println(d); // 输出 2.71828
System.out.println(f); // 输出 1.414
注意 float 类型需加 f 后缀。
科学计数法输出
使用 printf 的 %e 或 %E:
double sciNum = 0.00012345;
System.out.printf("%.3e", sciNum); // 输出 1.235e-04
四舍五入处理
结合 Math.round 或 BigDecimal 控制精度:
double original = 5.6789;
double rounded = Math.round(original * 100) / 100.0; // 保留两位
System.out.println(rounded); // 输出 5.68






