显示带 2 位小数的最终解决方案

Display final solution with 2 decimal places displayed

我正在编写一个程序,询问用户的年龄和他们有多少钱。如果他们已成年,他们将收到一条确认消息。如果不是,他们将被拒绝,并且将显示他们还剩 21 岁的年数。钱也一样。一杯啤酒5美元。如果用户没有足够的,它会告诉他们他们需要多少。但是...我无法生成在响应中显示 2 个小数位的值。我如何以美元金额或(例如 1.00)而不是 1.0 的形式显示解决方案或他们需要多少钱?

//import classes
import java.util.*;

public class beerLab
{
static Scanner console = new Scanner(System.in);

public static void main (String[] args)
{
    // Declares the price of beer and the age required to purchase beer.
    double beer = 5.00;
    double moneyGiven;
    int age = 21;
    int ageGiven;

    // Request the age from the client.
    System.out.println("Please type customer age: ");
    ageGiven = console.nextInt();

    if (ageGiven < 21)  // If the client is under 21 then their purchase will be denied.
        {
            System.out.println("No beer for you!" + "\n" + "Come back in " + (age - ageGiven) + " years" + "\n" + "Thank you for your patronage.");
            return;
        }

    // Request the the amount of money the client has.
    System.out.println("Type customer cash amount: ");
    moneyGiven = console.nextDouble();

    if (moneyGiven < beer)  // If the client doesn't provide enough money, the program will tell client how much money they need.
        {
          System.out.println("Sorry, you need " + (beer - moneyGiven) + " more." + "\n" + "Thank you for your patronage.");
        }

    if (ageGiven > 21 & moneyGiven >= beer)  // If the client is old enough and has enough money they can purchase the beer.
        {
            System.out.println("Congratulations, you can have some beer."  + "\n" + "Thank you for your patronage.");
        }
}
}

之前有人问过这个问题,因为 google 搜索 "java format decimal money" 会显示...

Java - format double value as dollar amount

您可以将 String.Format 与格式字符串一起使用,也可以使用 DecimalFormat class 或 NumberFormat class。

您可以使用以下语句:

System.out.format("Sorry, you need %.2f more." + "\n" + "Thank you for your patronage.\n", beer - moneyGiven);