java - 用小数点计数变化(可能是简单的解决方案)

原文 标签 java number-formatting

我有以下代码(我不太懂计算机,所以很温柔),使用户应该能够输入各个硬币金额,并且程序将告诉用户他们在所述硬币金额中有多少钱。

import java.util.*;

public class Coins {
  public static final Scanner CONSOLE = new Scanner(System.in);

  public static void main(String[] args) {

    System.out.println ("Lab 2 by Maria T Williams\n");

    quarterAmount( );
    dimeAmount( );
    nickelAmount( );
    pennyAmount( );
  }

  public static void quarterAmount( ) {
    System.out.print("Enter the number of quarters: ");
    int quarterNumber = CONSOLE.nextInt( );
    double amount = quarterNumber * 0.25;
    System.out.print(quarterNumber + " You have $" + amount);
    System.out.println(" worth of quarters.");
  }

  public static void dimeAmount( ) {
    System.out.print("Enter the number of dimes: ");
    int dimeNumber = CONSOLE.nextInt( );
    double amount = dimeNumber * .10;
    System.out.print(dimeNumber + " You have $" + amount);
    System.out.println(" worth of dimes.");
  }

  public static void nickelAmount( ) {
    System.out.print("Enter the number of nickels: ");
    int nickelNumber = CONSOLE.nextInt( );
    double amount = nickelNumber * 0.05;
    System.out.print(nickelNumber + " You have $" + amount);
    System.out.println(" worth of nickels.");
  }

  public static void pennyAmount( ) {
    System.out.print("Enter the number of pennies: ");
    int pennyNumber = CONSOLE.nextInt( );
    double amount = pennyNumber * 0.01;
    System.out.print(pennyNumber + " You have $" + amount);
    System.out.println(" worth of pennies.");
  }
}


如果我输入的金额在100位数中不是“ 0”,那很好。但是,如果我输入了两个季度,我将得到“ $ 0.5”而不是“ $ 0.50”。

最佳答案

您可以使用DecimalFormat强制将数字格式化为所需的格式。例如。:

DecimalFormat df = new DecimalFormat("#.00");
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + df.format(amount) + " worth of dimes.");

关于java - 用小数点计数变化(可能是简单的解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28307781/

相关文章:

java - KStream-KTable 使用 Exactly Once 配置内部连接丢失的消息

java - 使用DateTimeFormatter解析模式为“dd MMMMM uuuu”的日期

java - Android从http请求获取json引发IOException:尝试在关闭的流上读取

java - 使用Spring MVC发送html邮件的NULL指针异常

java - 计算2条语句之间的执行时间差

java - 如何在Velocity的NumberTool中使用自定义数字格式而不产生错误?

JavaScript:toLocaleString()

javascript - 如何使用货币和语言环境在 JavaScript 中格式化一个大数字(由字符串表示)?

java - 如何显示三位小数而不四舍五入?

javascript - 如何将我用逗号替换圆点的数字从字符串转换回十进制数字