首页 文章

Java中的2个小数位,上周开始在课堂上做Java

提问于
浏览
-4

开始在学校学习Java课程,并获得额外的学分,并需要帮助找出如何只有2位小数 . 感谢您的帮助 . 克里斯托弗

import java.util.Scanner;

public class ChapterTwoEx8 {public static void main(String [] args){

//Create a Scanner object to read keyboard input.
  Scanner keyboard = new Scanner(System.in);


//Declare Constants
  final double SALES_TAX_RATE = 0.07;
  final double TIP = 0.15;

//Declare Variables
   double yourMealsPrice;
   double wifeMealsPrice;
   double sum;
   double tip;
   double totalCostOfMeal;
   double salesTax;


 //Get the prices of the meals.
     System.out.println("Please enter the price of your wives meal.");
     wifeMealsPrice = keyboard.nextDouble();
     System.out.println("Please enter the price of your meal.");
     yourMealsPrice = keyboard.nextDouble();

  //Calculate cost of the meals.
     sum = (double) wifeMealsPrice + yourMealsPrice;

  //Calcute the sales tax
     salesTax = (double) sum * SALES_TAX_RATE;

  //Calcute tip
     tip = (double) sum * TIP;

  //Calcute total cost of meal
     totalCostOfMeal = (double) sum + tip + salesTax;

  System.out.println("Your meals were $ " + sum); 
  System.out.println("The total tax you paid is $ " + salesTax);
  System.out.println("The tip you should leave is $ " + tip);
  System.out.println("The amount of money you paid to keep your wife happy this night is $ " + totalCostOfMeal);






       }

}

1 回答

  • 0

    使用 NumberFormat

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    String formattedSum = nf.format(sum);
    System.out.println("Your meals were $ " + formattedSum); 
    System.out.println("The total tax you paid is $ " + nf.format(salesTax));
    System.out.println("The tip you should leave is $ " + nf.format(tip));
    System.out.println("The amount of money you paid to keep your wife happy this night is $ " + nf.format(totalCostOfMeal));
    

    或者,你可以摆脱美元符号,只使用 NumberFormat.getCurrencyInstance(); 而不是使用 NumberFormat.getInstance();

相关问题