repl.it
@mcuringa/

tip-calculator

ES6

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
 * tip-calulator.js
 * This example program helps the user
 * calculate the amount of tip to leave
 * on a restaurant bill.
 * by Matt Curinga
 * 15 Sep 2018 
 *
 */

/*
 Present the user with a welcome message.
*/
function welcome() {

  let msg = `
-----------------------------------
   Welcome to the Tip Calculator   
-----------------------------------
`;
  console.log(msg);
}

/*
  Calculate the tip on a bill, given the pct of the tip.
  Return the amount of the tip
*/
function calcTip(bill, pct) {
    // convert pct to a decimal and calculate
    let tip = bill * pct;
    
    // convert the tip to float with 2 decimal places
    tip = Number.parseFloat(tip);
    return tip;
}

/*
  Ask the user to enter the amount of the bill
  and return this amount as a <float>
*/
function askBillAmt() {
    let amt = window.prompt("How much was your total bill?");
    amt = Number.parseFloat(amt);

    return amt;
}

/*
  Allow the user to choose a tip amount from a menu.
*/
function askTipPct() {
  let pct = window.prompt("What percent tip do you want to leave?");
  // convert the pct from a whole number to a fraction
  pct /= 100;
  pct = Number.parseFloat(pct).toFixed(2);
  return pct;
}

function money(amt) {
  let dollars = "$" + Number.parseFloat(amt).toFixed(2);
  return dollars;
}

/*
  Prints a message to the user showing
  the result of the calculations.
*/    
function showResults(bill, tip, pct) {
  let total = tip + bill;

  console.log("Bill amount: " + money(bill) );
  // multiply % by 100 to convert back
  console.log("Tip percentage: " + (pct * 100) + "%" );
  console.log("Tip amount due: " + money(tip) );
  console.log("Total with tip: " + money(total) );

  console.log(`
-----------------------------------
             GOOD BYE      
-----------------------------------
`);
}

/*
  Read in the basic information, calcualte the tip
  and the share, then dispaly the results to the user.
*/
function main() {
    
    welcome();
    let myBill = askBillAmt();
    let pct = askTipPct();
    let tip = calcTip(myBill, pct);
    showResults(myBill, tip, pct);

}

main();
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie
?