add together 2 int vars with javascript - javascript

I'm working on a send / resend email button for the backend of my website and currently am trying to work out how to add 2 integers that I have made vars.
The script works fine as long as the integers are not 0, could anyone give me some pointers? I need it to show the total regardless of whether 1 of the vars is 0, thanks in advance
function sendResend() {
var selected = Array();
var selectedSend = $(".no:checked").length;
var selectedResend = $(".yes:checked").length;
var totalSendResend = parseInt(selectedSend) + parseInt(selectedSend);
$('input:checked').each(function () {
selected.push($(this).attr('name'));
});
var answer = confirm('You have selected ' + totalSendResend + ' emails. ' + selectedSend + ' New emails will be sent & ' + selectedResend + ' will be resent. Are you sure you want to continue?');
if (answer) {
alert(selected);
}
}

You have a typo in your code:
var totalSendResend = parseInt(selectedSend) + parseInt(selectedSend);
That adds the same values together; you wanted this:
var totalSendResend = selectedSend + selectedResend;
You didn't need the parseInt() cast at all, but if you did, you should always specify the radix as the second parameter, e.g. parseInt('0123', 10)

When you call ParseInt(myvalue) and myvalue begins with 0, it returns you an int considering value is expressed in octal.
To avoid this behavior always use parseInt(value, 10);
Edit : More info on how parseInt works no radix is specified :
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
See more here

Related

How to make 1 + 1 = 2 instead of 1 + 1 = 11 [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 7 years ago.
I am trying to add the number mathematically, but it keeps adding the number after it.
It takes the id number (begen), then it gets the number inside another div (kacbegen).
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (kacbegen + 1);
alert(toplam);
However, when doing the math (toplam), it alerts all the numbers.How to add the number mathematically ?
Convert it to number via adding a +:
var toplam = (+kacbegen + 1);
Unary plus (+)
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.
It looks like you're working with Strings (and thus a + b is the concatenation operator) when you want to be working with Number (so x + y would be addition)
Perform your favorite way to cast String to Number, e.g. a unary +x
var kacbegen = +$("#math" + begen).text();
You need to use parseInt to convert kacbegen, which is a String instance, to a Number:
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (parseInt(kacbegen) + 1);
alert(toplam);
The + operator, when used with a String on either side, will serve as a concatenation, calling Number.prototype.toString on 1.
You need to cast the contents to a number:
var contents = $("#math" + begen).text();
var kacbegen = parseFloat(contents);
You use kacbegen as a string. Please use as a integer use parseInt(kacbegen) + 1

Operator returning incorrect value?

var bedTime = $("bedtime").value;
var wakeUp = $("wakeup").value;
var Value = bedTime < wakeUp;
alert("is " + bedTime + " less than " + wakeUp + '? ' + Value);
My goal here to take user input through an html form (numeric only). This is what I wrote when I started running into the issue. Anything less than 10 except 1 will return the correct value, but anything over is incorrect. For example if bedTime = 10 and wakeUp = 9 it returns true. So just plugging in a few numbers leads me to believe that when comparing variables this way it only compares the first digit? Any workarounds? Thanks guys.
Try using parseInt() or parseFloat() to make sure you are comparing the same type of data.
var Value = parseInt(bedTime) < parseInt(wakeUp);
Comparing strings is different, for example '10' < '9' => true.

Append extra zeroes to decimal to make 4.5 look 4.500 but 4.5234 should be 4.5234

I have a value fetched from the database, it's like:
4.5 which should be 4.500
0.01 which should be 0.010
11 which should be 11.000
so I used this piece of code
sprintf("%.3f",(double)$html['camp_cpc'])
But here arised another problem. If $html['camp_cpc'] = '4.5234', then also it displays 4.523 instead of original value 4.5234
Also for other values with larger decimal like 0.346513, its only showing up to 0.346.
How can I solve this problem in JavaScript also?
Floats 4.5 and 4.500 correspond to the same number, so they cannot (and should not) be used/stored in a way that preserves the different representation. If you need to preserve the original representation given by a user, you need to store this field as a list (string) and convert to a float whenever you need the float value
In Javascript at least, this is an implementation of what I think you want:
function getValue(x, points) {
var str = x.toString();
// Convert to string
var idx = str.indexOf(".");
// If the number is an integer
if(!~idx) return str + "." + "0".repeat(points);
// Get the tail of the number
var end = str.substr(idx+1);
// If the tail exceeds the number of decimal places, return the full string
if(end.length > points) return str;
// Otherwise return the int + the tail + required number of zeroes
return str.substr(0, idx) + "." + end.substr(0, points) + "0".repeat(points-end.length);
}
console.log(getValue(4.5, 3)); //4.500
console.log(getValue(0.01, 3)); //0.010
console.log(getValue(11, 3)); //11.000
Working demo (Makes use of ES6 String.repeat for demonstration purposes)
The important thing to note here is that this is string manipulation. Once you start to say "I want the number to look like..." it's no longer a number, it's what you want to show the user.
This takes your number, converts it to the string and pads the end of the string with the appropriate number of zeroes. If the decimal exceeds the number of places required the full number is returned.
In PHP, use %0.3f — and you don't need to cast as (double)
<?php
echo sprintf("%0.3f", 4.5); // "4.500"
echo sprintf("%0.3f", 4.5234); // "4.523"
If you want to display 4 decimal places, use %0.4f
echo sprintf("%0.4f", 4.5); // "4.5000"
echo sprintf("%0.4f", 4.5234); // "4.5234"
To do this in JavaScript
(4.5).toFixed(3); // "4.500"
It could look sth. like this:
var n = [4.5234, 0.5, 0.11, 456.45];
var temp_n;
for(var i = 0; i < n.length; i++) {
temp_n = String(n[i]).split(".");
if(temp_n[1] == null || temp_n[1].length < 3) {
n[i] = n[i].toFixed(3);
}
}

Confusion with arithmetic operators in Javascript

While I do know that the following question is stupid simple, it is related to a specific situation that I have been unable to find through Google. The following code is in Javascript.
Suppose there is a variable
x = x + 1;
I can see from a tutorial that this is supposed to work. However, how are we supposed to use this variable in a calculation?
I have tried with the following codes
var name = name + 1;
alert(name);
The above outputs "NaN"; whatever that is...
var name = name + 1;
name = 2;
alert(name);
The above outputs 2 which is simply overriding the original variable.
name = prompt("input any number");
var name = name + 1
alert(name);
The above outputs the input provided + 1 as a string, i.e. 01 where the input is "0" without quotes.
I remember from a ruby lesson that we use .to_i in order to convert a string to an integer. How do we go about doing this in Javascript?
var name = name + 1;
The above code declares a new variable called name which contains whatever name contained before, plus 1. Since name only just came into existence, it doesn't have a numeric value ("Not A Number", or NaN). Adding 1 to NaN gives NaN.
+ means different things in different contexts. If the two operands are numbers, then it does addition. If one operand is a String, it does String concatenation, so
var x = "2"; // x is the String "2"
alert(x+2); // "22"
var x = 2; // x is the number 2
alert(x+2); // 4
If you want to convert a String to a number, you can do
if (x) x = parseInt(x, 10);
where the second argument is the radix (i.e. the base of the number system), and you should use it. If someone entered 02 for example, the radix prevents javascript from treating that as an octal (or other) number.
Of course, you always need to make sure your variables are defined before you use them. I bet your NaN result is coming from the variable not being defined.
Your issue is that you never initialize name. For example:
var name = 0;
alert(name); // Name is 0
name = name + 1;
alert(name); // Name is 1
If you don't initialize it, it will give you NaN: Not a Number.
To turn a string into a number, use parseInt or parseFloat:
var name = prompt("input any number"); // I input 3
name = parseFloat(name);
name = name + 1;
alert(name); // Name is 4
Use parseInt to convert a string to a number.
The line x = x + 1 says "take the existing value of x, add one to it, and store the resulting value back in x again".
The line var name = name + 1 is meaningless since name does not have an existing value when the statement is executed. It is the same as saying undefined + 1 which is NaN (Not a Number).
Here are some examples of how the + operator works in JavaScript:
1 + 2 // number + number is a number -> 3
"1" + 2 // string + anything is a string => "12"
1 + "2" // anything + string is a string => "12"
"1" + "2" // string + string is a string => "12"
NaN means "not a number". Since name has no value when it is first declared, saying "var name = name + 1" doesn't have a numerical meaning, since name is in the process of being declared when used for the first time.
In the second example, name is determined to be a string. Javascript isn't as sensitive to types as some other languages, so it uses + as a concatenation operator instead of a numerical one, since it makes more sense in context,

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories