My result in my jQuery gives NaN - javascript

I am getting NaN as result and its beacuse my jquery is multiplying numbers that look like "204,3 * 3"
How can I deal with it?
I cant change the price, so what can I do?
"234 * 2" works fine as soon as the number have ',' I get NaN.
<script type="text/javascript">
$('.quantity').keyup(function () {
var parent = $(this).parent(),
price = parent.find('.price').html(),
quantity = parent.find('.quantity').val(),
result = price * quantity;
parent.find('.price2').html(result);
});
</script>
<span class="price">69,9</span>
<input type="text" class="quantity">
<span class="price2">69,9</span>
<span class="total">Total:</span>
<div class="line2"></div>
Check my JSfiddle everything is there
Any kind of help is appreciated

Javascript uses North American number formatting, which means the , is used as a thousands seperator and the . is used decimal separator.
You have two solutions to your problem:
Teach your users to enter numbers like 1000.25
Write a routine to turn 1.000,25 into 1000.25
String.prototype.replace would be your friend on the second choice.

You are multiplying two strings here and not numbers..
Convert them using parseInt with radix
OR
Convert them using parseFloat
Change this line
result = price * quantity;
TO
result = parseInt(price,10) * parseInt(quantity,10);
OR
result = parseFloat(price) * parseFloat(quantity);

You're trying to multiply strings...use the parseFloat() and a replace() method as shown in your jsFiddle update here
$('.quantity').keyup(function () {
var parent = $(this).parent(),
price = parent.find('.price').html().replace(',', '.'),
quantity = parent.find('.quantity').val().replace(',','.'),
result = parseFloat(price) * parseFloat(quantity);
parent.find('.price2').html(result);
});

Related

Why is JS code decrementing like number (as expected) but incrementing/concatenating like a string when button is clicked [duplicate]

I can't seem to figure out why the subtraction is working in my code, but when I change the subtraction sign to an addition sign, I get a console error: Uncaught TypeError: undefined is not a function. Where is the error?
Here is a fiddle with the subtraction: http://jsfiddle.net/c8q7p6ac/
Here is a fiddle with the addition in place of the subtraction sign: http://jsfiddle.net/c8q7p6ac/1/
The subtraction sign and the addition sign are in the variable updatedNumber
HTML:
<div class="amount">$1000.00</div>
<input class="new-number" type="text">
<div class="button">Click</div>
jQuery:
$('.button').on('click', function(){
//get value of input
var newNumber = $('.new-number').val();
//get total number value
var totalNumber = $('.amount').text();
var getNumberOnly = totalNumber.indexOf('$') + 1;
var newTotalNumb = totalNumber.substr(getNumberOnly, totalNumber.length);
//add new number to total number
var updatedNumber = (newTotalNumb + newNumber).toFixed(2);
//and update total
$('.amount').html('$'+updatedNumber);
});
The subtraction works because JavaScript converts them to numbers. However, in case of addition, it converts them to strings as soon as one of the operands is a string.
You need to convert the string to a number:
var updatedNumber = (parseInt(newTotalNumb) + parseInt(newNumber)).toFixed(2);
While dealing with decimal points, you can also use parseFloat which will preserve the decimal points.
Here's the updated fiddle.

What is wrong with my simple math equation

I am trying to create a simple calculator that will return the amount of sales tax plus the amount after tax. If I input $80 and the sales tax is 7.5% I should get back an amount of $86 but instead I am getting $806 returned to me. I am unsure why.
//calculation
var total = (itemCost + (itemCost * salesTax/100));
total = Math.round(total)
you need var total = (parseInt(itemCost) + (parseInt(itemCost) * salesTax/100));
The thing is that when you retrieve the value, it is a string. Parse it as a number value by doing:
var salesTax = Number(document.getElementById("salesTax").value);
When you are getting the values of the text fields you have strings. Javascript does a lot of type inferring, that's why it almost works. Your expression gets translated to:
(String)"80" + ((String)"80"*(int)0.075)
(String)"80" + (int)6
And now the String operator+(String, Any) is called which is defined as string concatenation. Therefore you end up with "80" + "6" => "806".
If you for example would write:
"80" * "1" + "80" * "7.5"/"100" you would indeed get the expected result of 86.
But to be sure everything works as expected you should indeed parse the values from a string value to a number value (with parseInt resp. parseFloat).

numbers and text in same field

I can't get the numbers and text in same form field to force two decimal places or do Total figure.
This is the link.
I am trying to get the last 3 cells to work with two decimal places.
e.g. Total sq mt figure x Price should calculate the Cost cell.
Also want to get the Cost cell (NaN) working !
Thanks.
In general, you want to do something like this
function calc(val1, val2) { // this is NOT a replacement for your Calculate function
val1 = parseFloat(val1.replace(/[^\d\.-]/g, ''));
val2 = parseFloat(val2.replace(/[^\d\.-]/g, ''));
return (val1 * val2).toFixed(2);
}
NOTE: the above returns a STRING
and STOP redefining with Math.round in your code
var result = Math.round(num * 100.0) / 100.0;
Should format your number with two decimal places.

Calculate % discount of price. Javascript

Trying to build a Javascript %age Discount calculator for my webshop. The problem is that the calculator calculates some products wrong by 2-10%. Please help, whats wrong in the code?
<script type="text/javascript">
$(document).ready(function() {
/*
Least allowed discount to show.
*/
var minDiscount = 15;
$('.gridArticlePrices').each(function() {
/* Get ordinary price */
var oldPrice = $(this).children('.gridArticlePriceRegular').html();
/* Get sale price */
var newPrice = $(this).children('.gridArticlePrice').children('.reducedPrice').html();
if ((oldPrice) && (newPrice)) {
/* Convert to numbers instead of strings */
var oldPrice = parseInt(oldPrice.replace("/[^0-9]/g", ""));
var newPrice = parseInt(newPrice.replace("/[^0-9]/g", ""));
/* Calcuate the precentage, rounded of to 0 decimals */
var discount = Math.round(100 - ((newPrice / oldPrice) * 100));
/* If the precentage is higher than "var min Discount" then write out the discount next to the products price.*/
if (discount >= minDiscount) {
$(this).parent().after("<div class='discount'>-" + discount + "%</div>");
}
}
});
});
</script>
UPDATE:
My original suggestion to use parseFloat was assuming your prices included decimal components. As I see now, they are in fact integers, so parseInt works fine.
The actual issue is your replace() call isn't removing anything. You should remove the quotes around the regex, and then it will remove the extra characters you don't want.
var oldPrice = parseInt(oldPrice.replace(/[^0-9]/g, ""));
var newPrice = parseInt(newPrice.replace(/[^0-9]/g, ""));
Note: If you do need to handle decimal prices, you would need to add "." to you regex (so it doesn't get removed), and use parseFloat instead of parseInt.

Get price with in string with javascript using parseFloat an parseInt not working properly

I have retrieved a string and I extracted a decimal number from it using regex, e.g. 1.00 or 3.99. Now I wanna use these numbers for calculation. How can I convert those regex results into proper numbers so I can perform calculation? In the code below, every click should add the price to the previous total but it doesn't do the sum of numbers properly.
var SaveAfrica = {
init: function () {
this.addToBasket();
},
addToBasket: function () {
var featured = $('section.featured'),
bsktTotalSpan = $('.basket_total span.basket-qty'),
list = featured.find('ul'),
item = list.find('li');
featured.delegate('.buy-now', 'click', function (e) {
var thisElem = $(this),
qtyData = thisElem.closest('li').data('price'),
total = parseInt(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
e.preventDefault();
bsktTotalSpan.text(parseFloat(total));
console.log('The total is: total);
});
}
};
SaveAfrica.init();
The HTML where the digit is from:
<li data-price="£2.99"><img src="someImage.jpg" alt="some image" /></li>
Many thanks
Your problem may be that .match() returns an array of matches. So you might try something like:
parseFloat(qtyData.match(/[\d\.\d]+/i)[0]);
What does the sum come out to, if anything at all?
You may want to try the following instead:
total = parseFloat(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
That is, parse both of them to floats And explicitly define total as a float. Otherwise, the decimals might be getting truncated somewhere.
I think there is a typo in while getting the price from the element.
The code should be as below,
qtyData = thisElem.closest('li').data('data-price'),
You can simply multiply the string by 1 in order to convert it into a number:
num = '1.00' * 1 //result is the number 1

Categories