Why is my tip calculator multiplying my Total by 10? - javascript

I was just trying to make a simple tip calculator that I thought was going to take 5 seconds but something I'm not getting..
Why does this
subTotal = prompt('Total before Tip');
tipPercent = prompt('Percentage to Tip (Please use decimal)');
tip=tipPercent*subTotal;
total = subTotal+tip;
alert('Tip is ' + tip + ' Total is ' + total );
compute total to 10 times what it should be? I checked every other variable and it computes correctly except for subTotal + tip.

total = subTotal+tip;
This concatenates the subTotal string with the tip string.
Cast your values to float first before adding them together.
subTotal = parseFloat(prompt('Total before Tip'));
tipPercent = parseFloat(prompt('Percentage to Tip (Please use decimal)'));

JavaScript is treating subtotal and total as string not floats or integers
conversion will solve your issue like this
Here i am using the Number function to convert any string to the appropriate number type
subTotal = prompt('Total before Tip');
tipPercent = prompt('Percentage to Tip (Please use decimal)');
tip=tipPercent*subTotal;
total = Number(subTotal)+Number(tip);
alert('Tip is ' + tip + ' Total is ' + total );

your prompts are taking in strings and its simply concatenating the strings.
You need to convert the strings to numbers, in the case of your tip calculation js is converting the strings as numbers, but the addition for total its not. try something like this (add the parseInt() before the values to force JS to deal with them as integers):
total = parseInt(subTotal)+parseInt(tip);

Several answers above are correct. The input is STRING but you want to convert them to numbers to do the math on them.
Simplest solution is to convert them as you get the input from the user:
subTotal = Number(prompt('Total before Tip'));
tipPercent = Number(prompt('Percentage to Tip (Please use decimal)'));
Enter 20.00 then .15 will result in 23

The value coming from prompt is not integer. Read up: Window.prompt() - Web APIs | MDN
Convert it using parseInt() - JavaScript | MDN.
Also, you are missing the division by 100 while calculating the tip.
One more thing - if you are not declaring the variables using var, they will be global variables!
Check out this working code snippet:
var subTotal = parseInt(prompt('Total before Tip'));
var tipPercent = parseInt(prompt('Percentage to Tip (Please use decimal)'));
var tip = tipPercent * subTotal/100;
var total = subTotal + tip;
alert('Tip is ' + tip + ' Total is ' + total);

Related

Type Conversion Issue(?): How to grab html <span> tag's value and perform math on it?

How would I use javascript to take 30% off of the price and then append the discounted price under the old price? I'm getting tripped up on this.
Someone advised that I need to remove the $ some other way...?
HTML
<span class="price">$59.00</span>
JavaScript
var priceOne = parseInt(document.querySelector(".price").innerHTML);
var priceTwo = "$" + priceOne * .70;
document.querySelector(".price").innerHTML = priceTwo;
All tips or advice or solutions is appreciated!
JavaScript isn't able to parse strings to numbers if they have a string in it for whatever reason.
var price = document.getElementsByClassName('price')[0];
price.innerHTML += '<br>$' + (parseFloat(price.innerHTML.replace('$', ''))*0.7).toFixed(2);
<span class="price">$59.00</span>
You can use regular expressions
var priceOne = document.querySelector(".price").innerHTML;
// Use regular expression to strip out all non-numbers
var re = /\.\d+|\d\/\d|\d/g
var result = priceOne.match(re).join('');
//if in the united states, use this, else look on MDN for the correct formatting
document.querySelector(".price").innerHTML = (result*.7).toLocaleString("en-US",{style:"currency",currency:'USD'})
let oriprice = document.getElementById('price').innerHTML;
let priceOne = parseFloat(oriprice.substring(1,oriprice.length));
var priceTwo = "$" + (priceOne * .70).toFixed(2);
console.log(priceTwo)
<span id="price">$59.00 </span>
The problem is that your priceOne was NaN after parsed. Try to use subString to remove the first $ sign, and since it's a decimal amount, instead of using parseInt, use parseFloat and after calculating the 70% of it, apply toFixed on it

Get subtotal, apply discount, and show new amount

I have the code below but I'm having issues when the dollar amount has commas, for example $1,234.56. When I use the code below, it spits out 0.00. It should show the new subtotal with comma(s) if it's over a thousand.
var subtotal = $('.divWithAmount').text().replace("$",""); // Get the subtotal amount and remove the dollar sign
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(newSubtotal);
Thanks for your help!
The main reason it doesn't work is that the returned value from $('.divWithAmount').text() is of type String
To do operations it needs to be a number, and to enable that you also need to remove the comma and then parse it with e.g. parseFloat().
var subtotal = parseFloat($('div').text().replace("$","").replace(",",""));
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(parseFloat(newSubtotal).toLocaleString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>$51,234.56</div>
As commented, I updated my answer with toLocaleString, so the comma gets added back.
Here is a couple of ways how to localize the end result:
- Javascript Thousand Separator / string format
- Add thousands separator to auto sum
- convert a JavaScript string variable to decimal/money
to get number out of string value just do like this
var amount = "$1,234.56";
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));
once you get number then you can perform operation you want and it will resolve your issue that you are facing.

Regarding decimal in javascript

When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest
if(pos == -1)
{
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
var integer = enterCheckAmount.substring(0,pos);
var decimals = enterCheckAmount.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
enterCheckAmount = integer + '.' + decimals;
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.
Here is an example:
var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00
Thus there is no need to concatenate strings and add ".00" manually to your number.
Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:
var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11
If you have something similar like this, you are better off with this methods instead of cuting substrings.
I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.

toFixed Isn't Doing Anything

I'm teaching myself JavaScript and have run into a problem with toFixed(). I'm working through an amortization calculator; and, one of the steps returns a number with a huge number of decimal places. I'm trying to cut it down to 4 decimal places.
Be advised the sample code has a lot of explanatory HTML in it. It's only there so that I can work through the steps of the equation. Also, when I add one to the very long number, it adds the numeral one to end of the scientific notation.
var paymentamount;
var principal=250000;
var interestrate = 4.5;
var annualrate = interestrate/12;
var numberofpayments = 360;
document.write("This is the annuitized interest rate: "+ annualrate +"%");
document.write("<h3> Now we add 1 to the annualized interest rate</h3>");
var RplusOne = annualrate + 1;
document.write("<p> This is One Added to R: " + RplusOne + "%");
document.write("<h3>Next RplusOne is Raised to the power of N </h3>");
var RRaised = (Math.pow(RplusOne, numberofpayments)).toFixed(4);
document.write("<p>This gives us the following very long number, even thought it shouldn't: " + RRaised);
document.write("<h3>Now we add one to the very long number </h3>");
var RplusOne = RRaised + 1;
document.write("<p>Now we've added one: " + RplusOne);
From MDN's documentation:
If number is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
The problem is that you are using 4.5 as your interest rate instead of 0.045, so doing this:
Math.pow(4.5 / 12 + 1, 360)
gives you a huge number (6.151362770461608e+49 or 6.15 * 10^49 to be exact). Change your interest rate to 0.045 and you will get what you are expecting.
As for the var RplusOne = RRaised + 1 line, the problem here is that RRaised is a string because of toFixed. I would only call toFixed when you're displaying things, and not at any other time; the primary reason for this would be to avoid rounding errors in subsequent calculations, but has the added benefit that your variables remain numbers and not strings.

jQuery/Javascript splitting string calculation

I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity. These values are obviously multiplied together.
I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).
My code:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();
// calculate price
var sumValue = origprice * qty;
// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);
// update price
jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});
If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?
You'll want to use sumValue.toFixed(2)
var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70
.split does not exist on numeric types. You would have to use sumValue.toString().split('.'), and either way, this would be more inconvenient than simply sticking to .toFixed
You can use toFixed and parseInt() like so:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = parseInt(jQuery(".orig_price").val().substr(1),10);
var qty = parseInt(jQuery("#quantity").val(),10);
// calculate price
var sumValue = origprice * qty;
// split price
var price = sumValue.toFixed(2);
// update price
jQuery("#pricediv").html('£' + price);
jQuery("#pricediv").fadeIn(1500);
});
toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.

Categories

Resources