How to input decimal in prompt in JavaScript? - javascript

I am trying to make my program work, but something is wrong. I want to do a simple tax program, where I am calculating the total price including tax on X amount of items. I want to enter the values using prompt command in JavaScript. Here is my code:
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = prompt('Enter the phone price here...','');
quantity = prompt('Enter quantity here...','');
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = quantity * total
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
Everything works fine until I want to add decimal number as value. Quantity can't be decimal number of course, but, for example, the item price can be 119.95 dollars. When I enter this number directly in ti the script (without prompt) everything is fine, but when i declare prompt and enter the same value in the browser, it give me NaN as value which is not a number. Anyone got any explanation, and how can I fix this?

Try to debug your code, and you will see that problem not in parsing :)
You have STRING in phonePrice (the result of promt is string, let it be '10.5')
Then you have (tax = phonePrice * 0.05;) Result will be float (autoconverted) = 0.525
Then you have (total = phonePrice + tax;) Result will be STRING = "10.50.525" - because in '+' operator , if any argument STRING - all will be used as STRINGs
And then you got NaN in last '*' - because no one know the number "10.50.525" :) and result of float * NaN = NaN
Just try to convert input values.
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = parseFloat(prompt('Enter the phone price here...',''));
quantity = parseFloat(prompt('Enter quantity here...',''));
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = (quantity * total).toFixed(2); // Needed for correct result to money conversion
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');

You have to convert the input from the prompt, which is parsed as a string, into a number, with parseFloat and parseInt:
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = parseFloat(prompt('Enter the phone price here...',''));
quantity = parseInt(prompt('Enter quantity here...',''));
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = quantity * total
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
That said, you should instead count your money in cents instead of dollars, and use integers instead of floats, to avoid errors with floating-point accuracy.

Related

Jquery Adding tax to price with commas

I am having trouble calculating with commas in my price what would be de best solution to solve this?
I am console log the right price and want to get the tax.
example console log: "€1.652,89"
$(document).ajaxSuccess(function() {
var price = $('.yith_wcp_group_final_total').text();
console.log(price);
var tax = 21
var total = (price * tax) / 100;
$('#B_subtotal').html(total);
console.log(total);
});
//EDIT
$(document).ajaxSuccess(function() {
var price = $('.yith_wcp_group_final_total').text();
price = Number(price.replace(/[^0-9\.-]+/g,""));
console.log(price)
var tax = 21
var total = price * (100 + tax) / 100;
var roundup = total.toFixed(2);
$('#B_subtotal').html(roundup);
console.log(total);
console.log(roundup);
});
So i get 1.900,83
and after the calculation i get 2.3000043
How could I get the comma and dots back on the right place?
You are getting values in a string. Just convert the string into a float as we have a decimal point and apply regex as we have a currency sign in it. Regex will check the value and we will get the value in float which can be used with tax multiplication.
var price = $('.yith_wcp_group_final_total').text();
price = Number(price.replace(/[^0-9\.-]+/g,""));
console.log(price)
var tax = 21
var total = (price * tax) / 100;
$('#B_subtotal').html(total);
total = price + total
console.log(total.toLocaleString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to convert "€1.652,89" from "currency" to float. In this example I used the parseLocaleNumber function (https://stackoverflow.com/a/29273131/5334486).
This gives you float 1652.89 which can be correctly used to compute taxes and total.
You can then format total back to currency using Intl.NumberFormat() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
let price = "€1.652,89"
const taxPercent = 21
// REMOVE THE EURO SYMBOL FROM PRICE
price = price.substring(1)
// CONVERT LOCALIZED NUMBER TO FLOAT
const priceAsNumber = parseLocaleNumber(price, 'nl')
console.log(priceAsNumber) // 1652.89
// GET TAXES
const taxAmount = priceAsNumber * taxPercent / 100
console.log(taxAmount) // 347.1069
// GET TOTAL
const total = priceAsNumber + taxAmount
console.log(total) // 1999.9969
// FORMAT TOTAL TO CURRENCY
const totalRounded = new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(total)
console.log(totalRounded) // "€ 2.000,00"
//
// HELPER FUNCTION
//
// https://stackoverflow.com/a/29273131/5334486
//
function parseLocaleNumber(stringNumber, locale) {
var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/\p{Number}/gu, '');
var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/\p{Number}/gu, '');
return parseFloat(stringNumber
.replace(new RegExp('\\' + thousandSeparator, 'g'), '')
.replace(new RegExp('\\' + decimalSeparator), '.')
);
}

Dice values still concatenating after using parseInt/parseFloat

I am new to javascript and i'm trying to add values from a thrown dice using the click event listener. I have tried using parseInt/parseFloat to sum the numbers and show the values using inner.html but they keep concatenating. Here's my code
const dice=document.getElementsByClassName("btn-roll")[0];
let diceImg=document.querySelector("#dice-1");
let diceImg2=document.querySelector("#dice-2");
let p1CurrentScore=document.getElementById("current-0");
dice.addEventListener("click",function(){
let random1=Math.floor(Math.random()* 6) +1;
let random2=Math.floor(Math.random()* 6) +1;
diceImg.src="dice-" + random1 +".png";
diceImg2.src="dice-" + random2 +".png";
let totalDice=random1+random2;
let total=0;
total= total + (p1CurrentScore.innerHTML+=totalDice);
parseInt(total);
})
There is no need to create a total variable since that value is being stored in p1CurrentScore.innerHTML. What you want to do is set p1CurrentScore.innerHTML equal to its previous value plus totalDice.
Ultimately you want your listener to look something like the following:
dice.addEventListener("click",function(){
let random1=Math.floor(Math.random()* 6) +1;
let random2=Math.floor(Math.random()* 6) +1;
diceImg.src = "dice-" + random1 + ".png";
diceImg2.src = "dice-" + random2 + ".png";
let totalDice=random1+random2;
p1CurrentScore.innerHTML=parseInt(p1CurrentScore.innerHTML) + totalDice
})
Here is an example: https://470290.playcode.io
You should use parseInt to transform the text before you use the text in a math operation.
Like this:
const dice=document.getElementsByClassName("btn-roll")[0];
let diceImg=document.querySelector("#dice-1");
let diceImg2=document.querySelector("#dice-2");
let p1CurrentScore=document.getElementById("current-0");
dice.addEventListener("click",function(){
let random1 = Math.floor(Math.random()* 6) +1;
let random2 = Math.floor(Math.random()* 6) +1;
diceImg.src = "dice-" + random1 + ".png";
diceImg2.src = "dice-" + random2 + ".png";
let totalDice = random1 + random2;
let total = 0;
total = total + (parseInt(p1CurrentScore.innerHTML) += totalDice); // -> Use parseInt before the operation
// parseInt(total); -> Not necessary
})
Value of p1CurrentScore.innerHTML is a string and when you sum it, concatenating will be done and you get string as a result. Remember that when you are summing string and number you get concatenated string. So you need to parse that:
total= total + ((parseInt(p1CurrentScore.innerHTML))+=totalDice);
On the other hand if you subtract number from string which value is number it will be automatically converted to number. So you could do also something like (p1CurrentScore.innerHTML-0).
I hope this helps.

How to calculate tax percentage in jQuery?

This is my first time asking a question here, so I hope I'll do it correctly.
Just to give context, I'm developing a small website where lawyers can buy a digital version of some legal documents, but I'm having trouble calculating tax on the total cost.
The taxes are calculated with two rates used in the province of Quebec, Canada: GST (5%) and QST (9.975%). Both rates are calculated using the subtotal amount. Here's what I tried so far:
$("#formchoix #checkall").click(function () {
var tps = 0.05; //5%
var tvq = 0.09975; //9.975%
var subtotal = 0;
var total = 0;
if ($("#formchoix #checkall").is(':checked')) {
$("#formchoix input[type=checkbox].checkchoix").each(function () {
//check all forms
$(this).prop("checked", true);
$(".checknom").prop("checked", true);
$(".checkid").prop("checked", true);
subtotal += 15; //each form is 15$
$('#subtotal').html(subtotal + '.00$'); //subtotal shown to user
var taxes = subtotal * tps * tvq;
total = subtotal + taxes;
$('#totalcost').html(total.toFixed(2) + '$'); //total shown to user
$('#inputTotal').val(total.toFixed(2)); //value to be sent to server
});
} else {
$("#formchoix input[type=checkbox]").each(function () {
//reset everything: checkboxes, value and total shown to user
$(this).prop("checked", false);
$(".checknom").prop("checked", false);
$(".checkid").prop("checked", false);
subtotal = 0;
total = 0;
$('#subtotal').html('0.00$');
$('#totalcost').html('0.00$');
$('#inputTotal').val('0.00');
});
}
});
The above code doesn't give me the right number though. For example, if my subtotal is 30$, it will show 30.15$ instead of 30.49$ like it's supposed to (based on a tax calculator online).
I've also tried using values like 1.05 and 1.09975 and multiplicating them to the subtotal directly using total = subtotal * tps * tvq, but the total gave me 30.64$ (if the subtotal is 30$ like my previous example)
Clearly what I did is wrong, so how can I make sure the total is right?
30 * 0.05 * 0.09975 = 0.149625, which is rounded to 0.15 by calling toFixed(2). Math doesn't lie. As others suggested, you're taxing taxes.
var taxes = subtotal * tps * tvq;
total = subtotal + taxes;
should be changed to
total = subtotal + subtotal * tps + subtotal * tvq;
or
total = subtotal * (1 + tps + tvq);

What is causing this to return NaN?

This is supposed to be a simple order calculator, but for some reason it's just not working. Here's the code:
var name, product, price, discount, quantity;
var name = prompt("What is your name?", "Enter name");
var sentence = "Hello " + name + " please look through our available products and services before placing your order.";
alert(sentence);
var product = prompt("Please enter the name of the product you are looking to purchase from the table.", "Enter product");
var quantity = 1*prompt("How many " + product + " would you like to purchase?", "Enter quantity");
var cost = price * quantity;
var orderdiscount = price * discount * quantity;
var totalcost = cost - orderdiscount;
a = confirm(+ name + ", you ordered " + quantity + " of " + product + ". Is this correct?");
if (a) {
total = cost - (price * discount * quantity);
if (product === "ice cream cake") {
price = 20;
discount = .15;
} else if (product === "ice cream cone") {
price = 3;
discount = .01;
} else if (product === "small ice cream sundae") {
price = 5;
discount = .05;
} else if (product === "large ice cream sundae") {
price = 6;
discount = .05;
} else if (prompt = ("Sorry, " + name + ". You entered an invalid product. Refresh the page to reload and place the order again.")) {
}
}
else
{
alert("Refresh the page to reload and place a new order");
}
document.write("Thank you for placing an order with us, " + name + ".");
document.write("</br>");
document.write("The cost of buying " + quantity + " of " + product + " is " + cost + ".");
document.write("</br>");
document.write("The discount for this purchase is " + orderdiscount + ".");
document.write("</br>");
document.write("With the discount, your total order cost is " + totalcost + ".");
When I load the page and enter all of the necessary information, it returns:
"Thank you for placing an order with us, .
The cost of buying 1 of ice cream cake is NaN.
The discount for this purchase is NaN.
With the discount, your total order cost is NaN."
There are supposed to be calculated numbers in place of those NaNs. What in this code is causing this to happen?
You are doing your calculation before you are setting the values of your variables.
var cost = price * quantity; <-- calculation here
....
total = cost - (price * discount * quantity); <-- calculation here
if (product === "ice cream cake") {
price = 20;
discount = .15; <-- setting variable here
}
I would say it is because the value of price is not set anywhere and is left undefined by the time it is used.
Therefore when you calculate cost you are multiplying price (which is undefined) by quantity, and thus you will not get a valid result
The main problem I can see it the cost variable using the price variable before it has been assigned a value, first add simply change var cost = price * quantity; to this var cost = function(){return price*quantity;};
this way each time you call cost it will recalculate the price*quantity rather than at the top of the file before you've done the operations to get the price.
This happens because until here if (product === "ice cream cake") {
price = 20;
discount = .15;
} else if (product === "ice cream cone") {
price = 3;
discount = .01; price and discount are Null.
Use parseInt(..) on return value of :
prompt("How many " + product + " would you like to purchase?", "Enter quantity")
You're calculating cost before You set the price.
price is undefined for a kickoff, but even so, if the user was to order a dozen or twelve instead of 12 of whatever item he/she orders, you'll still end up with a NaN when quantity = 1*'a dozen';. Checking user input will always be a necessity
Is it the fact you're not declaring the price? If it's not a needed field for your user. Hide it.
Jonah

In JavaScript doing a simple shipping and handling calculation

I am having trouble with a simple JavaScript calculation. My document is supposed to add $1.50 to an order if it is $25 or less, or add 10% of the order if it is more then $25. The exact problem is:
Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
This is my code:
var price = window.prompt("What is the purchase price?", 0);
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
When testing I enter a number in the prompt box, and instead of calculating as if I entered a number it calculates as if I entered a string. i.e. i enter 19 and it gives me 191.5 or I enter 26 and it gives me 262.6
Using parseFloat will help you:
var price = parseFloat(window.prompt("What is the purchase price?", 0))
var shipping = parseFloat(calculateShipping(price));
var total = price +shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
See it working at: http://jsfiddle.net/e8U6W/
Also, a little-known put more performant way of doing this would be simply to -0:
var price =window.prompt("What is the purchase price?", 0) - 0;
(See: Is Subtracting Zero some sort of JavaScript performance trick?)
Be sure to comment this, though as its not as obvious to those reading your code as parseFloat
you can easily convert a string to a number
http://www.javascripter.net/faq/convert2.htm
basically JS provides parseInt and parseFloat methods...
Actually, you need to cast your text results into float values using parseFloat()
http://www.w3schools.com/jsref/jsref_parseFloat.asp
See my answer to the s/o question "Javascript adding two numbers incorrectly".
A bit of redundant multiplication, but your problem is that the numbers that are being inputted are treated as strings, not numbers. You have to convert them to floating point numbers:
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price)
{
if (price <= 25)
{
return 1.5;
} else {
return price / 10
}
}
window.alert("Your total is $" + total + ".");
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
var num = new Number(price);
if (num <= 25){
return 1.5;
} else{
return num * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
This should do it for you.

Categories