例如,我需要将
5.0
转换为 5
,或者将 4.3000
转换为 4.3
。5.0
转换为 5
,或者将 4.3000
转换为 4.3
。你应该使用DecimalFormat("0.#")
对于4.3000
Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
输出结果为:
4.3
如果是5.000,我们有
Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
输出结果为:
5
5.0
转换为 5
的情况,因为它会在数字末尾始终添加 .0
。 - Peter ElliottUse DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
使用一个格式字符串为“0.#”的DecimalFormat对象。