2 decimal places in Java, Just started doing Java in class last week -
started taking java class @ school , doing credit , need figuring out how have 2 decimal places. thank help. christopher
import java.util.scanner;
public class chaptertwoex8 { public static void main(string[] args) {
//create scanner object 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 prices of meals. system.out.println("please enter price of wives meal."); wifemealsprice = keyboard.nextdouble(); system.out.println("please enter price of meal."); yourmealsprice = keyboard.nextdouble(); //calculate cost of meals. sum = (double) wifemealsprice + yourmealsprice; //calcute 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 $ " + sum); system.out.println("the total tax paid $ " + salestax); system.out.println("the tip should leave $ " + tip); system.out.println("the amount of money paid keep wife happy night $ " + totalcostofmeal); }
}
use numberformat
numberformat nf = numberformat.getinstance(); nf.setmaximumfractiondigits(2); string formattedsum = nf.format(sum); system.out.println("your meals $ " + formattedsum); system.out.println("the total tax paid $ " + nf.format(salestax)); system.out.println("the tip should leave $ " + nf.format(tip)); system.out.println("the amount of money paid keep wife happy night $ " + nf.format(totalcostofmeal));
or, rid of dollar signs , use numberformat.getcurrencyinstance();
instead of using numberformat.getinstance();
Comments
Post a Comment