在 Java 中,如何删除整数时输出双精度数的小数位,而当它是浮点数时保留它们?

In Java, how do I remove the decimal places of an output double when it's an integer but keep them when it's a float?

用户输入一个字符串数值,它可以是 3.14 或 10 之类的任何值。当转换为 double 并打印回值时,我想 return 像 10 这样的整数值作为“ 10" 而不是 "10.0",但如果用户输入 3.14,我仍然希望 return 3.14。我知道这可以使用正则表达式并搜索字符串然后将值相应地转换为 int 或 double 来完成,但是有更简单的方法吗?这是我的简单代码:

    Scanner scanner = new Scanner(Systemin);
    System.out.println("Give a number:");
    double value = Double.parseDouble(scanner.nextLine());
    System.out.println("You gave the number " + value);
    

您可以为此使用 DecimalFormat。 # 表示如果数字存在,它将显示。

DecimalFormat format = new DecimalFormat("##.##");
System.out.println("You gave the number " + format.format(value));