Newbie student coder,
Here and I am developing a program that can alert program that once you type in the amount of money you give it will calculate the tip, and tax to get the total amount that the user owns. I have the base code down and divided it up into functions but when I put in a number it shows as unidentified.
Here is my code:
const TAXRATE=.095
const TIPRATE=.2
function foodCharge (foodCharge) {
return parseFloat(prompt("please enter the amount"));
}
foodCharge ();
function taxAmount (foodCharge,TAXRATE) {
return parseFloat(foodCharge*TAXRATE);
}
taxAmount();
function subAmount (foodCharge,taxAmount) {
return parseFloat(foodCharge+taxAmount);
}
subAmount ();
function tipAmount (TAXRATE,subAmount) {
return parseFloat (TAXRATE*subAmount);
}
tipAmount ();
function grandTotal (foodCharge, taxAmount, tipAmount) {
return grandTotal=parseFloat(foodCharge+taxAmount+tipAmount)
}
grandTotal ();
function finalCost(foodCharge,taxAmount, tipAmount, grandTotal ) {
alert ("Meal cost: "+ foodCharge + " \nTax: " + taxAmount + " \nTip: " +
tipAmount +" \nGrand total: " + grandTotal);
}
finalCost();
You need parseFloat function only when you parse float number from string. You don't need to parse result of regular math operation(if both numbers are not strings). When you pass function as a parameter to alert() you must pas it with brackets (), otherwise you pass the reference to a function.
If i correctly understand your question, here is your program:
const TAXRATE=0.095
const TIPRATE=0.2
function foodCharge (foodCharge) {
return parseFloat(prompt("please enter the amount"));
}
var charge = foodCharge ();
function taxAmount (charge, rate) {
return charge*rate;
}
var tax = taxAmount(charge, TAXRATE);
function subAmount (charge,tax) {
return charge+tax;
}
var amount = subAmount (charge,tax);
function tipAmount (rate,amount) {
return rate*amount;
}
var tip = tipAmount(TAXRATE,amount);
function grandTotal () {
return charge+tax+tip;
}
function finalCost() {
alert ("Meal cost: "+ charge + " \nTax: " + tax + " \nTip: " + amount +" \nGrand total: " + grandTotal());
}
finalCost();
You can adjust the function to be called within finalCost. Note, parseFloat() is only necessary at foodCharge function
const TAXRATE = .095
const TIPRATE = .2
function foodCharge() {
return parseFloat(prompt("please enter the amount"));
}
function taxAmount(charge, tax) {
return charge * tax;
}
function subAmount(charge, tax) {
return charge + tax;
}
function tipAmount(tip, sub) {
return tip * sub;
}
function grandTotal(charge, tax, tip) {
return charge + tax + tip;
}
function finalCost() {
let _foodCharge = foodCharge();
let _taxAmount = taxAmount(_foodCharge, TAXRATE);
let _subAmount = subAmount(_foodCharge, _taxAmount);
let _tipAmount = tipAmount(TIPRATE, _subAmount);
let _grandTotal = grandTotal(_foodCharge, _taxAmount, _tipAmount);
alert("Meal cost: " + _foodCharge + " \nTax: " + _taxAmount + " \nTip: " +
_tipAmount + " \nGrand total: " + _grandTotal);
}
finalCost();
Related
We are working on financial calculations.
JavaScript front-end code gives different results and C# backend gives different results. Please give me a solution to get the same result in both languages.
I mention two Cases in my example. The first case is not working and another is working.
I want results like C# code those are my expected results.
decimal TotalItemWiseRate = Convert.ToDecimal((Convert.ToDecimal(txtQuantity.Text) * Convert.ToDecimal(txtRate.Text)).ToString("0.00"));
myFunction();
function myFunction() {}
function setDecimalPoint(num) {
var setNumber = parseFloat(num);
if (isNaN(setNumber) || setNumber == 0) {
return setNumber;
} else {
var dotcontain = (setNumber).toString().includes(".");
if (dotcontain == true) {
var a = (setNumber).toString().indexOf(".");
setNumber = (setNumber).toString().substring(0, a + 4);
return (roundNumber(setNumber, 2));
} else {
return (roundNumber(setNumber, 2));
}
}
}
document.getElementById("Case1").innerHTML = "Javascript result: " + 756.05 * 43.5;
document.getElementById("Case11").innerHTML = "Current function: " + setDecimalPoint(756.05 * 43.5);
document.getElementById("Case111").innerHTML = "Calculater result: " + 32888.175;
document.getElementById("Case1111").innerHTML = "C#/My Expected Result: " + 32888.18;
document.getElementById("Case2").innerHTML = "Javascript result: " + 6864.48 / 100;
document.getElementById("Case22").innerHTML = "Current function: " + setDecimalPoint(6864.48 / 100);
document.getElementById("Case222").innerHTML = "Calculater result: " + 68.6448;
document.getElementById("Case2222").innerHTML = "C#/My Expected Result: " + 68.64;
function roundNumber(num, scale) {
if (!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if (+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
<p id="Case1"></p>
<p id="Case11"></p>
<p id="Case111"></p>
<p id="Case1111"></p>
<p id="Case2"></p>
<p id="Case22"></p>
<p id="Case222"></p>
<p id="Case2222"></p>
This single function is the simplest answer I found.
function setDecimalPoint(num) {
if (isNaN(parseFloat(num)))
return 0;
else {
var Number = parseFloat(num);
var multiplicator = Math.pow(10, 2);
Number = parseFloat((Number * multiplicator).toFixed(2));
return (Math.round(Number) / multiplicator);
}
}
first and foremost i'm new to javascript and coding. second, i'm coding a book store project with javascript with an alert message that shows each customer's total factor. but the alert message shows the code of my function "printFactor" insted of the string that is made by this function. this is my code:
function Book(name, writer, date, price)
{
this.name = name;
this.writer = writer;
this.date = date;
this.price = price;
}
function Customer(name, gender, turn)
{
this.name = name;
this.gender = gender;
this.turn = turn;
this.numberOfBooks = 0;
this.totalSum = 0;
this.bookList = [new Book("-", "-", "-", 0)];
//Functions.
this.addBook = function (newBook) {
this.numberOfBooks++;
this.bookList.push(newBook);
};
this.printFactor = function () {
var message = "";
if (this.numberOfBooks === 0) {
message = "No Books Has Been Added to Book List!";
return (message);
}
else {
message = this.name + " " + this.gender + " Number of Books: " + this.numberOfBooks + " Customer's Turn: " + this.turn + "\nBooks:\n";
var i;
var newMessage;
for (i = bookList.length - 1; i > 0; i--) {
newMessage = bookList[i].name + " " + bookList[i].writer + " " + bookList[i].date + " " + bookList[i].price.toString() +"\n" ;
message += newMessage;
this.totalSum += bookList[i].price;
this.bookList.pop();
}
newMessage = "Total Sum: " + this.totalSum;
message += newMessage;
return (message);
}
};
}
var book = new Book("Faramarz Bio", "Faramarz Falsafi Nejad", "1377/04/29", 13000);
var faramarz = new Customer("faramarz", "Male", 3);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
var m = faramarz.printFactor;
window.alert(m);
You need to invoke the function:
var m = faramarz.printFactor();
As is your variable m contains a reference to the function, but you need to call it to get the result.
var m = faramarz.printFactor();
window.alert(m);
You simply don't call your function, this should work.
var m = faramarz.printFactor()
Beside you reference an unexisting variable 'booklist', that should be "this.booklist"
for (i = this.bookList.length - 1; i > 0; i--) {
newMessage = this.bookList[i].name + " " + this.bookList[i].writer + " " + this.bookList[i].date + " " + this.bookList[i].price.toString() +"\n" ;
You need to actually call the function by adding () to the end, like this:
var m = faramarz.printFactor()
I am having a bit of an issue with my JavaScript Donation Calculator, It works well, however when I am calculating the percentage of 50, it comes up as $12.5 and I would like it to be $12.50, this also effects $7.50 it shows up at 7.5.
I have included the code below
// set the variables
var donationSubmit = document.getElementById('donationSubmit');
// turn the outputs into variables as I am sure they will be used more than once per page load
var afterCreditOutput = document.getElementById('afterCreditOutput')
var totalCostOutput = document.getElementById('totalCostOutput');
/* jquery stuffs */
$maxDonation = 1200
// calculate the value on keyup
$inputValue = $('input[name="donation_amount"]');
$('#customDonationAmount').keyup(function(){
if ($inputValue.val() > $maxDonation) {
$inputValue.val($maxDonation);
}
if ($inputValue.val() === "") {
afterCreditOutput.innerHTML = ("Please enter a value or choose from one of the preset values above");
totalCostOutput.innerHTML = ("");
}
calculateCustomTaxCredit();
});
// calculate the value on enter
/*
$inputValue.bind('keypress', function(e) {
if(e.which == 13) {
calculateCustomTaxCredit();
}
});
*/
/* end of jquery */
// validate the keystrokes and ensure the only things pressed are numbers
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
// super ugly and hacky but it does the job.
document.getElementById('donationAmount-20').onclick = applyButtonAmount;
document.getElementById('donationAmount-50').onclick = applyButtonAmount1;
document.getElementById('donationAmount-100').onclick = applyButtonAmount2;
document.getElementById('donationAmount-400').onclick = applyButtonAmount3;
document.getElementById('donationAmount-1200').onclick = applyButtonAmount4;
function applyButtonAmount() {
document.forms["donation-form"]["donation_amount"].value = (20);
calculateCustomTaxCredit()
}
function applyButtonAmount1() {
document.forms["donation-form"]["donation_amount"].value = (50);
calculateCustomTaxCredit()
}
function applyButtonAmount2() {
document.forms["donation-form"]["donation_amount"].value = (100);
calculateCustomTaxCredit()
}
function applyButtonAmount3() {
document.forms["donation-form"]["donation_amount"].value = (400);
calculateCustomTaxCredit()
}
function applyButtonAmount4() {
document.forms["donation-form"]["donation_amount"].value = (1200);
calculateCustomTaxCredit()
}
/* Where all the magic happens */
// Helper Funcs
// oh JavaScript why are you so bad at rounding.
function round(number, precision) {
var shift = function (number, precision, reverseShift) {
if (reverseShift) {
precision = -precision;
}
numArray = number.toString().split("e");
return +(numArray[0] + "e" + (numArray[1] ? (+numArray[1] + precision) : precision));
};
// number = shift(number, precision, false);
// number = Math.round(number);
// number = shift(number, precision, true);
return shift(Math.round(shift(number, precision, false)), precision, true);
}
// return a percentage
function per(num, amount){
return num*amount/100;
}
// calculate
function calculateCustomTaxCredit() {
var donationAmount = document.forms["donation-form"] ["donation_amount"].value;
// if there is nothing in the input then fail
if (donationAmount === "") {
afterCreditOutput.innerHTML = ("Please enter a value or choose a preset value");
// check has passed - this is a number
}else {
if(donationAmount <= 100 ) {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 25);
var credit = per(donationAmount, 75);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
console.log(donationAmount);
if(donationAmount == '50') {
alert('hi');
}
afterCreditOutput.innerHTML = ("Cost after Tax Credit:" + " <span
class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" +
donationAmount + "</span>");
//TESTING CODE
console.log('75% tax credit');
console.log('Money saved: ' + credit);
console.log('Money spent: ' + costAfterCredit);
console.log('Money saved: ' + cleanCredit + " CLEAN");
console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}else if(donationAmount > 100 && donationAmount <= 550) {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 50);
var credit = per(donationAmount, 50);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
afterCreditOutput.innerHTML = ("Cost after Tax Credit: Approx" + " <span class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" + donationAmount + "</span>");
//TESTING CODE
//console.log('75% tax credit');
//console.log('Money saved: ' + credit);
//console.log('Money spent: ' + costAfterCredit);
//console.log('Money saved: ' + cleanCredit + " CLEAN");
//console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}else {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 66.6666666666666);
var credit = per(donationAmount, 33.3333333333333);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
if(cleanCredit >= 500) {
cleanCostAfterCredit = donationAmount - 500;
}
afterCreditOutput.innerHTML = ("Cost after Tax Credit:" + " <span c class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" + donationAmount + "</span>");
//TESTING CODE
//console.log('75% tax credit');
//console.log('Money saved: ' + credit);
//console.log('Money spent: ' + costAfterCredit);
//console.log('Money saved: ' + cleanCredit + " CLEAN");
//console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}
}
};
Here is also a pastebin with more readable code:
goo.gl/UQZrik
In the end I am trying to have the variable cleanCostAfterCredit set to 12.50 instead of 12.5 when a calculation is done. Also if anyone can give me any tips on making my code more efficient I would really appreciate it. please lay on the constructive criticism :)
Use .toFixed(2) which will return a string representing the 2 decimals.
var result = 12.5;
var resultWithDecimals = result.toFixed(2);
The toFixed method formats floats but is not culture aware.
donationAmount.toFixed(2)
If you want to be culture aware, you should use toLocaleString
console.log(
// This uses the default locale
(12.5).toLocaleString(undefined, {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
);
console.log(
(1).toLocaleString('pt-br', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
);
This works tell I hit the tax function. Then I start getting
nan and undefined errors. Cant figure out why the tax function is not picking up the code from the other functions.
/ Saturday May 27 2017
{
// Global variables
var orderCount = 0;
var takeOrder = function (topping, crustType) {
// add one to order count
orderCount = orderCount + 1
return('Order: ' + crustType + ' pizza topped with ' + topping );
}
var getSubTotal = function(itemCount){
var subTatal = (itemCount * 7.5);
return (subTatal + ' subtotal of ' + ' itemCount ' + (itemCount));
}
var getTax = function (){
var subTatal = subTatal * 0.06;
// getTheTax = (subTatal * 0.06)
return subTatal + ' with tax of ' + (subTatal)
}
var getTotal = function (){
var myTotal = getSubTotal + getTax;
return ' tax ' + getTax + 'plus subtotal ' + getSubTotal() + ' is ' + (myTotal);
}
console.log(takeOrder('bacon', 'thin crust'));
console.log(takeOrder('cheese', 'thick crust'));
console.log(takeOrder('pepperoni', 'medium crust'));
console.log(getSubTotal(10));
console.log(' getTax ' + getTax());
console.log(getTotal());
}
This is the corrected version of your code.
var takeOrder = function(topping, crustType) {
console.log('Order: ' + crustType + ' pizza topped with ' + topping);
return 1;
}
var getSubTotal = function(orderCount) {
var subTotal = (orderCount * 7.5);
console.log('Subtotal of ' + subTotal.toFixed(2) + ' with item count ' + orderCount);
return subTotal;
}
var getTax = function(subTotal) {
var tax = subTotal * 0.06;
console.log('Tax is ' + tax.toFixed(2));
return tax;
}
var getTotal = function(subTotal, tax) {
var total = subTotal + tax;
console.log('Total is ' + total.toFixed(2));
return total;
}
var orderCount = 0;
orderCount += takeOrder(orderCount, 'bacon', 'thin crust');
orderCount += takeOrder('cheese', 'thick crust');
orderCount += takeOrder('pepperoni', 'medium crust');
var subTotal = getSubTotal(orderCount);
var tax = getTax(subTotal);
var total = getTotal(subTotal, tax);
Summary of corrections
Made functions return Number rather than String
Now all functions are almost pure functions (don't cause side-effects other than logging)
Formatted numbers prior to printing them by rounding them to the second decimal
Fixed typographic errors (tatal rather than total).
Added parenthesis to function invocations (e.g: getTax() rather than getTax
Removed redundant invocations
More
you are defining a variable, and assigning into it it's value times something.
var subTatal = subTatal * 0.06;
In this case, subTatal does not have a value.
I think you should read about variables and scopes.
Read the link below:
https://www.w3schools.com/js/js_scope.asp
Your both function is returning the string :
....
return subTatal + ' with tax of ' + (subTatal)
...
return ' tax ' + getTax + 'plus subtotal ' + getSubTotal() + ' is ' + (myTotal);
You can go through this blog for converting strings to number:
https://coderwall.com/p/5tlhmw/converting-strings-to-number-in-javascript-pitfalls
Please make sure the what is the type of value you want to be returned form the function to use it.
var subTatal = subTatal * 0.06;
is equivalent of
var subTatal = undefined;
subTatal = subTatal * 0.06;
note, this subTatal is not the same as the one defined outside the function (learn scope)
If you create a variable inside a function it will exists only inside that function, so if you call that variable from inside another it will be undefined.
There are two ways:
declare these variables as global at the top of your code just like orderCount
functions can have inputs and output, so you can pass to a function the variable you need and ask it to return the result, which can be saved into a variable and later used.
For example:
function getSubtotal(orderCount) {
var subtotal = //do something
return subtotal }
function getTax(subtotal) {
var tax = //calculate tax
return tax }
var subtotal = getSubtotal(orderCount)
var tax = getTax(subtotal)
I'm trying to use Math.round for the total to show only two decimals, but it doesn't work as intended. What am I doing wrong?
$(document).ready(function() {
var totalPrice = 0;
$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = parseFloat($frm.children(".priceInput").val());
var addAmount = parseFloat($frm.children(".amountInput").val());
if ($('.priceInput').val() == '') {
alert('Price can not be left blank');
};
if ($('.amountInput').val() == '') {
alert('Amount can not be left blank');
} else {
var div = $("<div>");
div.append("<p class='amount'>" + addAmount + "</p>", "<p class='product'> " + toAdd + " </p>", "<p class='price'>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
}
console.log(addAmount);
console.log(addPrice);
});
$(document).on("click", ".delete", function() {
/* var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= subAmount * subPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);*/
$(this).closest("div").remove();
console.log(subPrice);
console.log(subAmount);
});
$(document).on("mouseover", ".delete", function() {
var hoverAmount = parseFloat($(this).siblings(".amount").text());
var hoverPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= hoverAmount * hoverPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 0.4);
});
$(document).on("mouseout", ".delete", function() {
var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice += subAmount * subPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 1.0);
})
});
Since I'm using float, the numbers sometimes get changed into long decimals instead of the exact amount. I'm trying to prevent this by using Math.round. If anyone have another solution to the problem that would be appreciated too.
Use Number.prototype.toFixed() with 2 as argument, in order to round it to two decimals.
Just, remember that the returned value is a String:
let totalPrice = 4.655555;
totalPrice = totalPrice.toFixed(2);
console.log(totalPrice); // "4.66"
console.log(typeof totalPrice); // string
If you want to return a number, use Number(totalPrice.toFixed(2)) — just keep in mind that i.e: Number((7.005).toFixed(2)) will return 7 (without the decimal part)
If you work with currency it is better to use fixed point numbers for precision. There is no fixed-point number type in javascript, so consider using external libraries.
E.g. Big.js or bignumber.js