因为平时很少练习,所以考试两个小时答十道题,对于我来讲还是很费劲,并且平时没有很注意关于小数点的问题,平时几乎都是用printf来写,并没有挖掘好用的写法,今天来举例好用的方法:
1.String.format
double money = 123.456;
// 保留两位小数
String info = "您本次消费金额:" + String.format("%.2f", money) + " 元";
System.out.println(info);
// 输出:您本次消费金额:123.46 元
如果要四舍五入,就用上边这个方法
2.DecimalFormat 单独格式化数字(适合多次复用,统一格式)
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.00");
double score = 89.128;
String text = "期末总分为:" + df.format(score) + " 分";
System.out.println(text);
}
}
今日分享结束,下次见。