Jquery - set a variable with a decimal in front - javascript

In Jquery, how do you take a variable and set a second variable with a decimal in front of the value of the first variable.
For example I have a variable that is set from a form input values. I named this variable subTotal. Now I want to take that variable and set another variable with a decimal in front of it so I can calculate a percentage by multiplying another input value.
So here is some of the code for example
var subTotal = self.calculateTotalFor(elems);
total += (quantity - 1) * NewVariable;
self.calculateTotalFor(elems); comes from the input on the form
NewVariable would be Subtotal with a decimal in front.

Try :
var subTotal = self.calculateTotalFor(elems), total = 0;
total += (quantity - 1) * NewVariable;
or
total += parseFloat((quantity - 1) * NewVariable);

Try this
var NewVariable = parseFloat("." + Subtotal);
This will take "." and your Subtotal value and perform a string
append
parseFloat will convert the string to a floating point number

Related

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

How to round my values with Math.ceil()?

got the following code:
var total = 0;
var $parent = $(this).closest('ul');
$parent.find('input:checked').each(function() {
total += parseInt($(this).val() * parseInt(115, 10) / parseInt(100, 10) / parseInt(36, 10));
});
$parent.find('span[class^=total]').html(Math.ceil(total));
The code checks the value of my inputs and with parseInt i convert them to another value (its a fixed price converted to monthly costs over 3 years).
This works but the value which i output in my html at the end wont get rounded up:
So my question is, how i can round up the value of my html output.
You're using parseInt() which will round down to the nearest int by default. If the original values are floating points you need to use parseFloat() instead.
$parent.find('input:checked').each(function() {
total += parseFloat($(this).val()) * 115 / 100 / 36;
});
Working example
Also note that you don't need to call parseInt() or parseFloat() on literal integer values.

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.

multiplying values

Im using the following method to add up text boxes. I have tried changing multiple things and cant seem to multiply two text box values! essential I want 2 text box that values are multiplied and displayed in a third text box. I want this value to be fluid aka change when the number changes! I was using this code because i may be multiplying more then one thing but if this is too much of a hassle i will live with just multiplying two at a time
The code im using to add is
<!--adding script #-->
<script>
$(document).ready(function(){
calculateSum();
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
var total = document.getElementById("subtotal").value == "";
var total = document.getElementById("subtotal").value = sum;
}
<!--END adding script #-->
I tried setting the last line to
var times1 = document.getElementById(subtotal);
var times2 = document.getElementById(tax);
var equal = times1.value * times2.value;
and then changing var total1 = document.getElementById("total1").value = sum9; to var total1 = document.getElementById("total1").value = equal;
The text boxes id are subtotal and tax the box im trying to update is total1.
Thanks alot!
On every keyup, instead of getting all values and adding them explicitly, it is better to deduct the previous value of the corresponding input and add the current updated value to sum..
Also, if subtotal is correctly calculated, then the multipication operation what ever you have done should work correctly..
Please find the following jsfiddle where the sum is calculated as explained above along with multiplying the tax..
http://jsfiddle.net/tgvrs_santhosh/77uxK/1/
Let me know if you still face the issue..
Instead of this
if(!isNaN(this.value) && this.value.length!=0) {
I think a regular expression may work better because you are using string values
if (/^([-]?((\d+)|(\d+\.\d+)|(\.\d+)))$/.test(this.value)) {
I haven't tested this regex, but you should be able to find a good regex to test for valid numbers if this one doesn't work for some reason. Also I noticed you have a == after that getElementById.
I'm not totally certain it matters, but you can do sum += (this.value * 1) instead of parseFloat.
update
Try this var equal = ($("#subtotal").val() * 1) * ($("#tax").val() * 1);
I found your question very confusing, but I think what you're trying to say is you want to add up all the .txt fields to get a sub-total, then multiply that sub-total by a tax rate to get a total. If so, then you already know the sub-total is a valid number due to the way you calculate it, so then:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
If your tax field is not an input then use .text() instead of .val().
Your existing code is rather more complicated than it needs to be. You can do this:
$(document).ready(function(){
calculateSum();
// you don't need an .each() loop, you can bind a keyup handler
// to all elements in the jQuery object in one step, and you don't
// need the anonymous function since it does nothing but call calculateSum:
$(".txt").keyup(calculateSum);
});
function calculateSum() {
var sum = 0,
val;
//iterate through each textboxes and add the values
$(".txt").each(function() {
// you don't need to test for NaN: just attempt to convert this.value
// to a number with the unary plus operator and if the result is not
// a number the expression val = +this.value will be falsy
if(val = +this.value)
sum += val;
});
$("#sum").html(sum.toFixed(2));
var tax = +$("#tax").val();
$("#total1").html((tax ? sum * tax : sum).toFixed(2));
}
For some reason the unary plus operator used throughout my answer is not widely known, but I prefer it to parseFloat().

Javascript returning NaN

I'm attempting to display a subtotal each time a customer enters a quantity. However, when I loop through my inputs, I get a NaN as the total. I believe it may be the way I'm declaring the subtotal variable in my script, but I haven't come across this before:
$('.item-qty input').bind('keyup', function(){
var subtotal = 0.0;
$('.item-qty input').each(function(){
var class = $(this).attr('id');
var qty = $(this).val();
var price = $('.'+class).html();
price = parseFloat(price);
qty = parseInt(qty);
subtotal = subtotal + (price * qty);
});
$('.subtotal input').val(subtotal);
});
parseFloat and parseInt can return NaN if the first character of the string cannot be converted to a number.
So, I would safeguard against it like this (NaN is a falsy value):
price = parseFloat(price) || 0;
qty = parseInt(qty, 10) || 0;
Arithmetic operations on numbers with the value NaN almost always result in NaN (NaN + 5 will result in NaN.) That means, if only one of the input cannot be parsed by parseFloat or parseInt, your current code would end up calculating NaN for the subtotal.
It's already been mentioned in the comments (by Felix mostly) but I think it's worth the emphasis as these are important concerns:
Always pass the radix argument to the parseInt function;
Do not use class for variable names: It's a reserved (not used, but reserved) keyword;
Don't expect the subtotal to be perfectly accurate unless you do your calculations in cents.

Categories