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?

huangapple go评论73阅读模式
英文:

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。当转换为双精度浮点数并打印出值时,我希望将整数值(如10)仅显示为"10",而不是"10.0",但如果用户输入3.14,我仍希望返回3.14。我知道可以使用正则表达式来搜索字符串,然后根据需要将值转换为整数或双精度浮点数,但是否有更简单的方法来做到这一点呢?以下是我的简单代码:

Scanner scanner = new Scanner(Systemin);
System.out.println("给一个数字:");
double value = Double.parseDouble(scanner.nextLine());
System.out.println("你输入的数字是:" + value);
英文:

A user inputs a string numeric value and it can be anything like 3.14 or 10. When converting to a double and printing the value back, I'd like to return integer values like 10 as just "10" and not "10.0" but if the user enters 3.14 I'd still like to return 3.14. I know this could be done using regex and searching the string and then converting the values to an int or double accordingly, but is there an easier way to do this? Here is my simple code:

    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);

答案1

得分: 1

你可以使用DecimalFormat来实现。#表示如果数字存在,它将被显示。

DecimalFormat format = new DecimalFormat("##.##");
System.out.println("您输入了数字 " + format.format(value));
英文:

You can use DecimalFormat for that. # means if the number is present it will display.

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

huangapple
  • 本文由 发表于 2020年9月19日 10:21:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63964681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定