利用String.format可以格式化输出字符串
方法签名
public static String format(String format, Object... args);
常用的占位符
%d
整数%s
字符串%f
浮点数
示例
// 输出浮点数
String.format("%f", 3.1415926)
// 3.141593
// 保留零位小数
String.format("%.0f", 3.1415926)
3
// 保留一位小数
String.format("%.1f", 3.1415926)
// 3.1
// 保留两位小数
String.format("%.2f", 3.1415926)
// 3.14
完整代码
package com.example.demo;
public class Demo {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 3.1415926));
// 3.14
}
}