Simple JavaScript addition issues - javascript

I'm not so good with JS and for some reason when I try to add two fields together it joins them rather than adding the sum together.. this is the code I'm trying to use..
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
The totalVal is echoing/alerting out 68.50378.00 rather than adding them together.. could someone please tell me where I've gone wrong? :( The idea is to update the "total" textfield with totalVal, but I haven't gotten that far yet!

You need to convert your values to a float before adding them:
var totalVal = parseFloat(postage) + parseFloat(subtotal);
EDIT: Here's a complete example that includes a check for NaN:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var postageAsFloat = isNaN(postage) ? 0.0 : postage;
var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
var totalVal = postageAsFloat + subtotalAsFloat;
alert(postage);
alert(subtotal);
alert(totalVal);
};

Try converting the numbers to floats:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};

Everyone else has the right idea with parseFloat.
I just wanted to mention that I prefer to clean up numeric values like this (as opposed to parsing with substr):
var postageVal = document.getElementById('postage').value; //$68.50
var postage = parseFloat(postageVal.replace(/[^0-9.]/g, ''));
That replace call will remove any characters from the string except 0-9 and . (period). Not the /g at the end of the regex. That's important because, without it, only the first matching occurrence will be replaced.

parseFloat does the trick.
var postage = parseFloat(postageVal.substr(1));
var subtotal = parseFloat(subtotalVal.substr(1));

It's treating postage and subtotal as strings and concatenating them. You could try something like this:
var totalVal = 0+postage+subtotal;
That should force it into number mode.
However this could lead to problems if the values do not end up being numbers. You should run it through the proper number parsing functions and add checks to make sure they parsed correctly or else you will end up with NaN.

You need to parse the number first. This should work.
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat( postageVal.substr(1) ); //68.50
var subtotal = parseFloat( subtotalVal.substr(1) ); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};

Unary plus should work:
var totalVal = (+postage) + (+subtotal);
But you probably intended your postage and subtotal variables to be numbers rather than strings, so...
var postage = +postageVal.substr(1); //68.50
var subtotal = +subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;

I haven't tested your code so there may be other issues but the fix below using parseFloat should stop the concatenation and add the numbers together.
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = parseFloat(postage)+parseFloat(subtotal);
alert(postage);
alert(subtotal);
alert(totalVal);
};

Having had the same sort of trouble I examined the JS parseFloat and parseInt functions and found them to be badly developed.
So therefore I prevent the whole problem by multiplying the element's value's * 1 before adding them. This forces JS to treat the result as numeric even if the value's were empty, so that it can be properly handled. As follows:
var TEMP = (1 * el_1.value) + (1 * el_2.value);
document.getElementById("el_tot").value = TEMP;
Assuming you see that "el_1" et al are the fieldnames in the form.

Thanks for all the answers! I'll try them out, I'm sure they're better than my solution:
<script type="text/javascript">
function calculateTotal() {
var postageVal = document.cart.postage.value;
var subtotalVal = document.cart.subtotal.value;
var postage = postageVal.substr(1);
var subtotal = subtotalVal.substr(1);
var totalVal = Number(postage)+Number(subtotal);
document.cart.total.value = "$"+totalVal.toFixed(2);
};
</script>

1.simple javascript addition program
<!DOCTYPE html>
<html>
<body>
<p>This calculation perfoms an addition, and returns the result by using a JavaScript. Check for a demo</p>
<form>
Enter no 1:<input type="text" name="a"><br>
Enter no 2:<input type="text" name="b"><br>
& nbsp;
<button onclick="calc(this.form)">Calculate</button>
</form>
<script>
function calc(form)
{
var a=eval(form.a.value);
var b=eval(form.b.value);
var c=a+b;
alert("The sum is " + c);
}
</script>
</body>
</html>

Related

Javascript Number formating winthout numbers after comma

I am trying this script to calculate and print the result in a form input readonly. While this works fine i need the numbers to be shown like this: 2.000.000 instead of 2.000.000.00. I need those 2 zeros at the end gone. I googled it but all I find are solutions with the comma intact. As this script is very basic and simple i hope that for my problem there is a very simple and basic solution.
<script>
getPrice = function() {
var numVal1 = Number(document.getElementById("price").value);
var numVal2 = Number(document.getElementById("discount").value) ;
var totalValue = numVal1 * numVal2
document.getElementById("total").value = totalValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&.');
}
</script>
Have you tried this :
totalValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&.').slice(0, -3)

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

session storage number variable stored as string

I'm trying to store js number variables using sessionstorage but when I retrieve the variables from storage they behave like string variables when I add them together. I think this might have something to do with how I'm storing the variable using sessionStorage.setItem but not sure
I've saved the code at http://codepen.io/MHUMPHRI/pen/bpXpPm
Any help much appreciated. Cheers. Mike
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
OUTPUT TOTAL IS:
<div id="TotalOutput"></div>
<br>
<script>
$(document).ready(function () {
InputTotals()
OutputTotals()
});
</script>
</html>
<script>
var input1 = 222
var input2 = 111
var input3 = 777
var input4 = 777
function InputTotals() {
var totalA = input1 + input2;
var totalB = input3 + input4;
sessionStorage.setItem("TotalA", totalA);
sessionStorage.setItem("TotalB", totalB);
}
function OutputTotals() {
var output1 = sessionStorage.getItem("TotalA");
var output2 = sessionStorage.getItem("TotalB");
var totaloutput = output1 + output2;
$("#TotalOutput").html(totaloutput);
}
</script>
Use parseInt (with radix 10, to be compatible with older browsers) to parse a string to get an integer. Use parseFloat if you're dealing with decimals.
var output1 = parseInt(sessionStorage.getItem("TotalA"), 10);
Number(var) should work to define as number. Worked for me.

there is some mistake in the javascript and that is how to get output?

how to get output?
there is some problem in the code that is i am not able to get out answer.
and i can't figure that is my mistake
<!Doctypehtml>
<html>
<title>new html</title>
<head>
</head>
<body>
<script >
var number = document.getElementById("num1");
var number2 = document.getElementById("num2");
var out = document.getElementById("output");
number.addEventListener("input", sol);
number2.addEventListener("input", sol);
function sol(){
var one = parseint(number.value);
var two = parseint(number2.value);
out.innerHTML = one+two;
}
</script>
<input id="num1">+<input id="num2">
<p id="output"></p>
</body>
</html>
The function is parseInt (with a capital I) not parseint as mentioned Correctly by #Dai
var one = parseInt(number.value);
var two = parseInt(number2.value);
Here is the Fiddle
And also reason to use textcontext over the innerHTML
innerHTML parses content as HTML and takes longer.
textContent uses straight text, does not parse HTML, and is faster.
Using isNaN() function determines whether a value is an illegal number (Not-a-Number).
if (!isNaN(three))
{
//if its a valid number try to display the value to the output
}
Change parseint to parseInt:
$(document).ready(function () {
var number = document.getElementById("num1");
var number2 = document.getElementById("num2");
var out = document.getElementById("output");
number.addEventListener("input", sol);
number2.addEventListener("input", sol);
function sol() {
var one = parseInt(number.value);
var two = parseInt(number2.value);
out.innerHTML = one + two;
}
});
Demo
Hey first Of all try embedding the java script file into you code except writing an inline JS code because if the code is large then you may get stuck up in assigning events to ID by dertermining the ID values in the HTML.
Secondly, yes you have errors in the following code
function sol(){
var one = parseint(number.value);
var two = parseint(number2.value);
out.innerHTML = one+two;
}
/*the following lines need to be changed /
/ parseInt*/
var one = parseInt(number.value);
var two = parseInt(number2.value);
Thankyou !!
I guess this is what exactly you looking for:
Working : Demo
var number = document.getElementById("num1");
var number2 = document.getElementById("num2");
var out = document.getElementById("output");
function sol(){
var one = parseInt(number.value);
var two = parseInt(number2.value);
if(number2.value != '')
{out.innerHTML = one+two;}
else
{out.innerHTML = '';}
}
<input id="num1">+<input id="num2" onkeyup="sol()">
<p id="output"></p>

JavaScript string to integer

I'm making a conversion app and I keep getting return Not a Number (NaN)
function conversion() {
var bill = document.getElementById('bill');
var mates = document.getElementById('mates');
console.log(bill);
console.log(mates);
var pay = parseInt(bill)/parseInt(mates);
alert("Each mate pays: " + pay);
}
Can't figure out why it won't return in integer.
You're trying to parse an HTML Element into an integer. What you probably want is to get the values from the inputs:
var bill = document.getElementById('bill').value;
var mates = document.getElementById('mates').value;
you need to get the values, now you are parsing entire elements.
function conversion() {
var bill = document.getElementById('bill').value; // <---
var mates = document.getElementById('mates').value; // <---
console.log(bill);
console.log(mates);
var pay = parseInt(bill)/parseInt(mates);
alert("Each mate pays: " + pay);
}

Categories

Resources