session storage number variable stored as string - javascript

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.

Related

JS how to use two arithmetic operators

i want to get data from input fields and do two arithmetic operations at same time (1)multiplication (2) addition. Multiplication is working but when i try to do 2nd operation i get some error. for example 2*2+2=6 but when i try the answer comes 42.
my code is here .
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =$('#sfpm').val();
var b = $('#snom').val();
var c = $("#bonus").val();
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>
As you can see in this example the first box will cause multiplication, but the rest will concatenate ( simply append to ) the last digit present, which increases length but doesn't do any mathematical operation.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm">
snom<input id="snom">
bonus<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =$('#sfpm').val();
var b = $('#snom').val();
var c = $("#bonus").val();
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>
This is because you're adding two strings together instead of numbers. Strings added together look like this:
let str = "Hello ", str2= "world!";
console.log(str + str2);
So it makes sense that they append. Numbers look like this:
console.log(1 + 5);
Which does what you expect, but the important thing to realize is that the + operator has multiple functions. it can either append or perform math. The difference as to what type of operation is performed is based solely on the type of the data you're using.
a string will append
a number will add
So in your code when you get the value using .val() - what's happening is that you're getting string values, not number values. To fix this we can do a few different things.
parseInt or Number methods will convert the values from .val() into integers:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm">
snom<input id="snom">
bonus<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a = parseInt($('#sfpm').val());
var b = Number($('#snom').val());
var c = parseInt($("#bonus").val());
var taamount = a*b+c ;
$('#staamount').val(taamount || 0);
});
});
</script>
One other way to coerce a string to a number is to simply place the + operator before the value. This will cause the interpreter to automatically try to change the value into a number.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm"> snom
<input id="snom"> bonus
<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function() {
$('#sfpm,#snom,#bonus').keyup(function() {
var a = +$('#sfpm').val();
var b = +$('#snom').val();
var c = +$("#bonus").val();
var taamount = a * b + c;
$('#staamount').val(taamount || 0);
});
});
</script>
Use parseInt() to ensure you are getting the int version of the value, it looks like it is adding c as a string
You're trying to operate on string.
You're doing something '2' + '0' which will result as '20' not 2.
Because here + operator does the concatenation of two string not arithmetic addition
Change it number.
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =Number($('#sfpm').val());
var b = Number($('#snom').val());
var c = Number($("#bonus").val());
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>

Javascript variables not adding the result, variables are act as string why?

Why error ?
expected results = 1360000
result = 1000000360000
<script>
function hitungJumlah() {
var jumlah = document.getElementById("pinjam").value;
var lama = document.getElementById("kembalinya").value;
var bunga = lama * 12/100;
var biaya = document.getElementById("biaya").value = jumlah * bunga;
document.getElementById("total").value = jumlah + biaya;
}
</script>
Because it's read your data as string use parseInt() function to make your data as Integer
Try with this
parseInt(jumlah) + parseInt(biaya)
Beacuse 1000000 and 360000 act as string . + is also used for concatination in javascript
Because the * operator wont type coerce like + operator. Besides you may not have to use document.getElementById() all the time. You might simply do;
<script>
function hitungJumlah() {
var jumlah = Number(pinjam.value),
lama = Number(kembalinya.value),
bunga = lama * 12/100;
biaya.value = jumlah * bunga;
total.value = jumlah + biaya;
}
</script>
Though parseInt() and Number() have differences. While parseInt("42*10") would result 42, as a number object constructor Number("42*10") would result a NaN.
So be careful playing with them.

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>

My VAT calculation is wrong

I'm trying to do a function for making a small calcul with vat.
So I have the following code:
<script type="text/javascript">
function calcdebours()
{
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva= Math.round((((ht_tva)*(taux))/100)*100)/100;
;
if(taux=='')
{
taux=0;
}
if(ht_no_tva=='')
{
ht_no_tva=0;
}
if(ht_tva=='')
{
ht_tva=0;
}
document.getElementById('debours_montant_tva').value = tva ;
document.getElementById('debours_montant_ttc').value = (tva) + parseInt(ht_tva)+ parseInt(ht_no_tva)
}
</script>
And below the fiddle:
http://jsfiddle.net/6zzRZ/
But for all it make the wrong calculation, I think it does not count the cent.
I've tried using just var 1 + var 2 but it just used to concatenate the number sor I use the parseInt function.
It has worked but the result is wrong for any kind of amount.
The trouble is that I tried parseDecimal but it say that this function does not exist.
Any kind of help will be much appreciated.
Try parseFloat. Or use the unitary + like this: var ht_no_tva = +document.getElementById('debours_montant_ht_no_tva').value; This gives JavaScript the hint that it should treat the value as a number.
Use parseFloat() instead of parseDouble:
http://www.w3schools.com/jsref/jsref_parsefloat.asp

Simple JavaScript addition issues

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>

Categories

Resources