How to add together numerical values that are stored in strings? - javascript

I'm trying to add 1 to my JavaScript variable, but the following code doesn't give expected results:
var val1 = document.getElementById('<%= rng1.ClientID %>');
var val2 = val1.value + "1";
alert(val2.value);
How can I do this?

you can use the function parseInt() to transform the string stored in val1.value into a number:
var val2 = parseInt(val1.value) + 1;
Note that Number(val1.value) will also convert your value into a number.
-edit-
As yc suggest, is highly recommended to use parseInt(val1.value, 10) + 1; because if your string starts with a "0" the string is interpreted as octal. eg. parseInt("0123") == 83 and not 123

The simplest and also preferred way would be to use + to cast to a number.
Examples:
+'234'; // 234
+'042'; // 42! It does not convert to octal
In your case:
var val1 = +(document.getElementById('<%= rng1.ClientID %>').value); // () added just for the looks
var val2 = val1.value + 1; // if val1 is 5, val2 will be 6 hooray!
alert(val2); // just val2, since it's a plain number not an html input element

parseInt($('.scpContainer').height()+200)

you must add number, so try it without quotes :-)

In an external JavaScript file you can't use the <%=ControlID.ClientID %> to get the client id.
If there you using an external JavaScript file you need to pass client id value to that function.

Related

Add together numbers in separate DIVs

(obligatory I'm new to this) What I am trying to do is...
Fetch the contents (a number) of the DIV ID.
Add those numbers together
Print them in the "at" DIV.
I know it should be pretty darn simple. But I cant wrap my head around why it isn't working. I want to learn WHY it's not working. I dont necessarily want you guys to write it for me. I want to learn. Here is my code...
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
It outputs properly, but it's just not adding the numbers in the DIVs together. It's placing them side by side rather than adding them together.
That's because you are only doing a string concatenation.
You need to transform the values to numbers as .innerHTML() returns a string. This is how should your operation:
var addopt = +ac + +ah + +af;
Note:
It's better to use .innetrText() or .textContent() over .innerHTML to avoid getting HTML markups inside your elements if there are any into the result.
This happens a lot. What you need to do is convert to integer because it reads it as a string using ParseInt (variable) or ParsefLoat (variable) ParsefLoat (variable) can also use .toFixed (decimal_places)
You have to parse the content of the divs to a number, as the innerHTML returns a string.
So either var addopt = +ac + +ah + +af; or var addopt = parseInt(ac) + parseInt(ah) + parseInt(af); should work for you.
You need to parse the innerHTML to integers or floats to be able to do mathematical operations on them. Check the below code that takes the text and parses it to ints:
var addopt = parseInt(ac) + parseInt(ah) + parseInt(af);
You try to additionnal strings instead of numbers.
innerHTML return the string in a HTML element.
You should parseInt or parseFloat the content to have numbers.
<script>
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
// Values are taken as string and mus be converted to int.
// We check also that a value is not undefined.
ac = isNaN(parseInt(ac)) ? 0 : parseInt(ac);
ah = isNaN(parseInt(ah)) ? 0 : parseInt(ah);
af = isNaN(parseInt(af)) ? 0 : parseInt(af);
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
</script>
The contents of your divs are strings, even though the represent numbers. So if your divs have the values '1', '2' and '3' adding them togther gives you '123' rather than 6 as you might expect. Have a look at the parseInt function to see how you can turn your strings into numbers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

get wrong result function jquery javascript

I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());

How to add one to a variable to make 2 not 11

Currently this makes 11. It's for a slideshow and the var "n" equals 1 by default
function forward() {
document.getElementsByClassName("img")[0].setAttribute("class","imgout");
setTimeout( function() {
var n1 = document.getElementById("img").getAttribute("data-number");
var n=n1+1;
document.getElementById("img").setAttribute("data-number", n);
document.getElementById("img").setAttribute("src", "images/" + n + ".jpg");
document.getElementsByClassName("imgout")[0].setAttribute("class","img");
}, 500)
}
Use parseInt():
var n = parseInt(n1, 10) + 1;
Instead of:
var n=n1+1;
When n1 will be a string, because it came from the DOM, you need to convert n1 to an integer. There are many ways to do this, and really you should probably use a regular expression to validate that n1 contains what you expect first, but that being said you can try any of the following:
var n=parseInt(n1, 10)+1;
var n=(n1*1)+1;
var n=(+n1)+1;
As an aside the regex for validating the input from the DOM might be something such as:
/^-?\d+$/
Use Number():
var n = Number("1");
FIDDLE
parseInt - good choice. Also you can do
var n = n-0+1
Just remember that of you have different types "+" will convert to string and "-" will convert to numbers
Convert n1 to number as it is a string like ~~n1. The ~~n1 form is good if you know you want an integer (a 32-bit integer).
Second way is to use Number() function i.e. Number(n1) will convert n1 value into a string.
var n=parseInt(n)+1;
Documentation
Fiddle

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

jQuery / javascript variable in if statement not working

I have a variable as such:
var is_last = $('.paging a:last').attr('rel');
this returns '-400' which is correct.
However, i need to add 200 to this so the answer is '-200'
if i do this:
var is_last = $('.paging a:last').attr('rel')+200;
the variable is now '-400200'
How can i pass the variable as a value?
A.
You need to parse the output of .attr(), it to an integer first using parseInt() so you're dealing with a number (and not a string), like this:
var is_last = parseInt($('.paging a:last').attr('rel'), 10) + 200;
I reckon that #Nick Craver is correct and that parseInt is the more correct answer, but as a quick-and-dirty alternative you can also convince javascript that a variable is a number and not a string by multiplying by 1:
var x = parseInt("-400", 10) + 200;
var y = ("-400" * 1) + 200;
alert(x);
alert(y);

Categories

Resources