无需额外命令即可删除尾随零

时间:2018-10-09 22:17:45

标签: java printf

如何在不使用十进制格式程序或任何其他额外命令的情况下消除双精度尾随零?为什么会出现额外的零?我正在尝试制作一张桌子作为作业,但数字后面不能有多余的零。不允许有其他命令。

public class CelctoFaren {

    public static void main (String[] args) {
        double celsius = -40;
        double farenheit;
        double counter = celsius;

        while (counter < 0) {
            farenheit = 1.8 * celsius + 32;
            System.out.printf ("%fC\tis\t%fF\n", celsius, farenheit);
            celsius += 1;
            counter++;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

看看printf format string specification,您应该找到所需的内容。例如,您可以使用%f代替%0.2f并将double值限制为两位小数。

现在得到所有尾随零的原因是%f不限制打印多少小数位,而double值有很多小数。

答案 1 :(得分:0)

您也可以使用String.format示例:

 System.out.println(String.format("%0.2f %0.2f", celsius, farenheit));