simple calculation of integer and decimal number in jquery - javascript

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.
Does anyone know what is the issue?
Thank you.
$(function(){ // bind the recalc function to the quantity fields
$("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');
$("#quantity").bind('keyup', recalc);
function recalc(){
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = quantity * creditPrice;
$("#total").text(total);
}});

Use parseFloat on the values, and alert each one individually to test.
A few other (unrelated) improvements:
Use keyup() function:
$("#quantity").keyup(recalc);
Make function anonymous:
$("#quantity").keyup(function(){...});
Use $(this) on #quantity in the function to avoid calling the jQuery selector again
You could also consider condensing this into a single line of code:
$("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));
To zero-pad you might try something toFixed():
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
I got this snippet from the following site
http://www.mredkj.com/javascript/numberFormat.html
Hope this helps.

use
parseFloat
before calculation on both numbers which parses a string argument and returns a floating point number.
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);

If you are interested in whole number only you can use this function instead:
parseInt

Related

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.

How to calculate with numbers in jquery?

I am wanting to subtract some values of inputs with the total price.
The code:
$('.calculate-resterend').click(function(e) {
e.preventDefault();
var contant = $('.checkout-contant').val();
var pin = $('.checkout-pin').val();
var creditcard = $('.checkout-creditcard').val();
var waardebon = $('.checkout-waardebon').val();
var totalprice = $('.total.final-price.price').text();
alert(contant - totalprice);
});
But this returns NaN. I figure it's because total price is .text();,
but what is the correct way to substract between these things.
Lets say var contant has a value of 2000,98
and the total price has a value of 2400,99
I want it to return 400,01.
Use Number()
alert(Number(contant) - Number(totalprice));
If you also want to remove comman(,)
alert(Number(contant.replace(/\,/g,'')) - Number(totalprice.replace(/\,/g,'')));
You may have to convert one of your values using parseInt. You can try the following:
totalprice = parseInt(totalprice)
And then proceed to do your simple subtraction like before. You could also try to make your own price attribute on the HTML element itself and the fetch the attribute value instead like .attr("price"). Not sure if that would return a string as well.
try to convert your value by using parseint()
eg:- parseint(your_value)

missing zero in cents on one field javascript

there is one form field that is missing the zero in the cents. the form field is total.
the others are ok ( total_t and total_tax work fine ). i have tried a few things but it either stops working or just doesnt add the zero on the end of the calculation.
example being if a product is 0.20 it shows as 0.2 and misses the zero on the end in the total field. but the tax and after tax work fine
<script>
$('document').ready(function(){
$('.input-qty').on('input', function(){
var total = 0;
var qty = $(this).val();
var price_single = $(this).parent().parent().parent().find('.input-price-single').val();
$(this).parent().parent().parent().find('.input-price-total').val(parseFloat(qty * price_single).toFixed(2));
$('.input-price-total').each(function(){
total += Number($(this).val());
});
total_t = Number(parseFloat(total).toFixed(2));
total_tax = parseFloat((total_t * 0.10) + total_t).toFixed(2);
$('.input-total').val(total_t);
$('.input-total-tax').val(total_tax);
});
});
</script>
so i guess it would be this section here:
$(this).parent().parent().parent().find('.input-price-total').val(parseFloat(qty * price_single).toFixed(2));
$('.input-price-total').each(function(){
total += Number($(this).val());
There are a few things 'wrong' with your code. (And it's all in your comment section too).
I'll try to fix them putting the answers together (but the credits really go to the people who suggested it.)
<script>
$('document').ready(function(){
$('.input-qty').on('input', function(){
var total = 0;
var qty = $(this).val();
var parent = $(this).parent().parent().parent();
var price_single = $(parent).find('.input-price-single').val();
$(parent).find('.input-price-total').val((qty * price_single).toFixed(2));
$('.input-price-total').each(function(){
total += Number($(this).val());
});
$('.input-total').val(total.toFixed(2));
$('.input-total-tax').val((total * 1.10).toFixed(2));
});
});
</script>
I don't have the corresponding HTML for this, so I can't try it on a fiddle or anything, so this is solely from the top of my head. (Untested)
Your error rests in the lines:
total_t = Number(parseFloat(total).toFixed(2));
$('.input-total').val(total_t);
In these lines, you assign the result of your total-calculation parsed to a float, parsed to a string and then cast to a number (and that's where the real problem sits).
That means, instead of assigning a string (with the correct amount of digits) to the field, you're assigning a variable of type 'number', which assumes the formatting it deems as 'right'.
Now, if you don't want to take all my corrections (after all they're quite a few and also untested), you might roll with something like:
total_t = Number(parseFloat(total));
$('.input-total').val(total_t.toFixed(2));
This should fix your problem.

Javascript .val() issue

When I enter a decimal for chance, it returns NaN for pay and profit. Any idea why? Also what would I need to do to round profit to the second decimal.
Thanks.
$(document).ready(function(){
function updateValues() {
// Grab all the value just incase they're needed.
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/(chance+0.5)) *100)/100;
// Calculate the new profit.
profit = bet*pay-bet;
// Set the new input values.
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
$('#chance').keyup(updateValues);
$('#bet').keyup(updateValues);
$('#pay').keyup(updateValues);
$('#profit').keyup(updateValues);
});
First make use of parseFloat or (parseInt if you don't need float values).
function updateValues() {
var chance = parseFloat($('#chance').val());
var bet = parseFloat($('#bet').val());
var pay = parseFloat($('#pay').val());
var profit = parseFloat($('#profit').val());
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/(chance+0.5)) *100)/100;
}
Also what would I need to do to round profit to the second decimal.
you can do this:
profit = bet*pay-bet;
profit = profit.toFixed(2);
You need to use parseFloat to properly work with the values, which by default are strings:
var chance = parseFloat($('#pay').val());
/*same for other values*/
To round the profit to 2 decimals, you can use toFixed on that number, which again converts it back to a string.
3.123.toFixed(2) = "3.12"
Try using parseFloat:
var chance = parseFloat($("#Chance").val());
You can also use toFixed to specify the number of decimal places.
Edit
You need to modify chance:
chance = parseFloat(chance);
You can see this working here:
http://jsfiddle.net/U8bpX/

length does not work after multiplication

Edit: Solution: http://jsfiddle.net/VnXtP/
Why dosent this work?
http://jsfiddle.net/uc7kT/
<input type="text" name="item_quantity" id="item_quantity" value="1" />
<input type="text" name="item_price" id="item_price" value="24998" hidden="hidden" />
$('#item_quantity').change(function() {
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
var total = quantity * price;
alert(total.length);
});
Length is defined for strings, not numbers. If you wish to do this as a mathematical operation, you must convert the input strings to numbers first. If you actually want the length of the number string (I don't know why you would), you need to convert the number to a string first:
$('#item_quantity').change(function() {
var quantity = parseInt($('#item_quantity').val(), 10);
var price = parseFloat($('#item_price').val());
var total = quantity * price;
alert(total.toString().length);
});
Use:
alert(total);
Instead of:
alert(total.length);
You may also want to consider converting the values of the input to a float, or integer value before performing the math.
http://jsfiddle.net/samliew/uc7kT/5/
total is a number. It does not have the property "length".
Try
alert(total);
I guess that is what you want.
In javascript a number is a number and a string is a string.
What can be sometimes confusing is that a number can automagically become a string when that is needed (for example adding a string to it).
Numbers do not have a length property, strings instead do. Also in javascript when you ask an object for a property that is not present normally you just get the undefined value.
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
item_quantity and item_price are text inputs, and you need to change it to Integer before you multiply. use parseInt() to do it.
var quantity = parseInt($('#item_quantity').val(),10);
var price = parseInt($('#item_price').val(),10);
and use alert(total); not alert(total.length);

Categories

Resources