Javascript Maths showing wrong number [duplicate] - javascript

This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 7 years ago.
I am trying to do maths and i been getting values such as 200052 i.e if i add 2000+52, where it should be 2052. What am i doing wrong or missing something?
//get value of amount eneterd
amount = document.getElementById("amount").value;
//apply percentage
if(rateExcel.checked = true){
total= parseINT((amount/100) * 5);
total= total + parseINT(amount);
//still i get the same, like 20052 instead of 252.
};
Edit: The input is integer, not a string! I see many people trying to be ninja about telling to use parseINT(), but i tried and it didn't work.

You fix this by forcing the amount variable to become an int since it's probably received as a string.:
total = total + parseInt(amount);

Your amount is a string so you need to convert your amount to number using
total= total + Number(amount);

//get value of amount eneterd
amount = document.getElementById("amount").value;
//apply percentage
if(rateExcel.checked == true){
total= (parseInt(amount,10)/100) * 5;
total= total + parseInt(amount,10);
};

Related

Receiving NaN when trying to make calculations with 4 Digits Numbers in Javascript

Here is the javascript code for calculating the price of the item the problem is that whenever the price is 4 digits the value that return is NaN.
totalDiv: function() {
var porcentage = +this.vmodel.form.percentage / 100;
this.calculatedTotal = +this.vmodel.form.purchase_price / (1 - porcentage);
this.vmodel.form.sell_price += this.calculatedTotal;
return +this.calculatedTotal.toFixed(2);
},
Anyone could help me to understand what I'm doing wrong?
Thanks.

Average calculator finding strange and incorrect numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 3 years ago.
I am trying to make an average calculator. This is my code for it:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
}
var average = total / data.length;
document.write(average);
It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.
You need to take a number, not a string value from the prompt.
The easiest was is to take an unary plus + for converting a number as string to a number
data.push(+newdata);
// ^
Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.
It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

Why is my tip calculator multiplying my Total by 10?

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);

Javascript sum of values in table [duplicate]

This question already has answers here:
How to format a float in javascript?
(14 answers)
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 9 years ago.
I've succesfully used this code to calculate sums in a table:
var $overall = 0;
$("tr.sum").each(function()
{
var $qnt = $(this).find("td").eq(0);
var $price = $(this).find("td").eq(1);
console.log($qnt+" | "+$price);
var sum = parseFloat($price.text()) * parseFloat($qnt.text());
$(this).find("td").eq(2).text(sum);
$overall+= sum;
});
$("#total").text($overall); });
I changed one line to avoid rounding errors:
var sum = parseFloat((parseFloat($price.text().replace(',', '.')) * parseFloat($qnt.text().replace(',', '.'))).toFixed(2));
It works fine. But I can't solve the problem to round the total sum to two decimal places.
$("#total").text($overall);
I tried toFixed(2). But this results in a string and not a number.
Any help would be appreciated!
Thanks, Mike
after doing all calculation make it like this
$overall.toFixed(2);

why count the price is not right when the qty equals 10? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript’s Math broken?
from this question:
get all the input value and make an addition
there is a promotion:
buy 1 each price is 14.37, buy 10 the price is 13.28, buy 20 each price is 10.78.....
now i want to do a counter.http://down123.xxmn.com/count.htm
the counter write the whole price.now, there is something wrong with my code.
if i fill 5 in an input box, then fill 5 in another input box. the whole price isn't 132.8. why?
if i remove a number in an input box, the whole price doesn't change. thank you
the code:
var $inputs = jQuery('.liste_couleur_qty li input');
$inputs.keyup(function() {
var result = 0;
$inputs.each(function(){
result += parseInt(this.value, 10);
});
var JsonData =[{"price_id":"1","website_id":"0","price_qty":1,"price":"14.37"},
{"price_id":"2","website_id":"0","price_qty":10,"price":"13.28"},
{"price_id":"3","website_id":"0","price_qty":20,"price":"10.78"},
{"price_id":"3","website_id":"0","price_qty":50,"price":"9.23"},
{"price_id":"3","website_id":"0","price_qty":100,"price":"7.91"}
]
var sorted = JsonData.sort(function(a,b){return a.price_qty - b.price_qty;});
var i=0;
while(i < sorted.length && sorted[i].price_qty <= result){i++;}
var price = sorted[i-1].price;
price= price*result;
jQuery('#qtyvalue').html("Total price is " + price);
});
now, when the qty is 9, the right price is 9*14.37. but my counter is not right.
The answer you are looking for is a method called .toFixed()
Try changing the last line that sets your price to
jQuery('#qtyvalue').html("Total price is " + price.toFixed(2));
and that should work.
Update:
When you empty any text box, your code stops working since the value is '' rather than 0, and can't be added. Update the 5th line of the code to this:
result += parseInt((this.value === '' ? 0 : this.value), 10);

Categories

Resources