Addition in React JSX - A + B [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
Output: 55
How can I force it to output 10?

You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.

the simplest:
dots = dots*1+5;
the dots will be converted to number.

DON'T FORGET - Use parseFloat(); if your dealing with decimals.

I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

parseInt() should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10 in parseInt(number, 10) specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.

This also works for you:
dots -= -5;

You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}

Number()
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity

its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.

After trying most of the answers here without success for my particular case, I came up with this:
dots = -(-dots - 5);
The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.

UPDATED since this was last downvoted....
I only saw the portion
var dots = 5
function increase(){
dots = dots+5;
}
before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.
One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:
<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>
where the event would give an error and clear the last character if the value is not a number:
<script type="text/javascript">
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
var yourChar = String.fromCharCode();
if (yourChar != "0" &&
yourChar != "1" &&
yourChar != "2" &&
yourChar != "3" &&
yourChar != "4" &&
yourChar != "5" &&
yourChar != "6" &&
yourChar != "7" &&
yourChar != "8" &&
yourChar != "9")
{
alert ('The character was not a number');
var source = event.target || event.srcElement;
source.value = source.value.substring(0,source.value-2);
}
}
</script>
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use eval():
dots = eval(dots) + 5;

Related

Write program that uses a while loop to get first and last numbers from the string, calculate the sum, removing these numbers then doing it again [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
Output: 55
How can I force it to output 10?
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
DON'T FORGET - Use parseFloat(); if your dealing with decimals.
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
parseInt() should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10 in parseInt(number, 10) specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
This also works for you:
dots -= -5;
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Number()
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.
After trying most of the answers here without success for my particular case, I came up with this:
dots = -(-dots - 5);
The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.
UPDATED since this was last downvoted....
I only saw the portion
var dots = 5
function increase(){
dots = dots+5;
}
before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.
One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:
<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>
where the event would give an error and clear the last character if the value is not a number:
<script type="text/javascript">
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
var yourChar = String.fromCharCode();
if (yourChar != "0" &&
yourChar != "1" &&
yourChar != "2" &&
yourChar != "3" &&
yourChar != "4" &&
yourChar != "5" &&
yourChar != "6" &&
yourChar != "7" &&
yourChar != "8" &&
yourChar != "9")
{
alert ('The character was not a number');
var source = event.target || event.srcElement;
source.value = source.value.substring(0,source.value-2);
}
}
</script>
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use eval():
dots = eval(dots) + 5;

Check for numeric value or range

A input-field could have values like:
23
23-45
No I want to correct the value:
string.replace(/[^\d-]/g,'');
But that doesn't correct these values:
-45
23-
45-23
10-110
All these values are incorrect (The valid values are from 0-100 (as they are percentage values), so 110 is unvalid). So for that cases I want the user to have a second look at the input field...
I guess I have to create a second RegEx for these unvalid cases, right?
function to return true if a percentage is represented by whole numbers, where if a dash is included the first number is less than the second, and both numbers are between 0 and 100:
function isValidPercentage(input) {
var mat = /^(\d+)(?:-(\d+))?$/.exec(input + "");
if (mat !== null && ((mat[2] === undefined && mat[1] < 101) || (mat[1] < mat[2] && mat[2] < 101))) {
return true;
}
return false;
}
Edit#1: To force the false return if either number is greater than 100
Edit#2: Fixed errors, cleaned up the code a bit
Say you have an input (#perc) and a button (#calc), then try:
document.querySelector('#calc').addEventListener('click', calculate);
function calculate() {
// replace all non numeric values in the input with nothing
// and convert it to a Number (using the + operator).
var value = +(document.querySelector('#perc').value.replace(/[^\d]/g, ''));
// now you can check the value
alert( !isNaN(value) && value >= 0 && value <= 100
? 'ok ' + value
: 'not ok ' + value );
}
The SO-inline code inserter is not working, so you'll have to try it out yourself.

format decimal in javascript

i would like to format decimal values to specific format as like
1.23 should be shown as 0001.23 using javascript. is there any specific functions like toPrecision(), tofixed() in javascript to handle these kind of formatting or any pointers to go ahead with any solutions?
here preceeding decimal is dynamic one.
for example :
i have 2 values :
first value : 99.4545
second value : 100.32
in this second value has higher length (3)before decimal and first value has higher length after decimal(4). so subtracted result(0.8655) of this should be formatted as ###.#### (000.8685)
thank you
Just make a function that does what you want it to. Here is an example you can expand on if you want.
function pad(num, padSize){
var numString = "" + num.split('.')[0];
if(num.length < padSize){
var numZeroes = padSize-num.length;
var zeroes = "";
while(numZeroes){zeroes += "0"; numZeroes--;}
return zeroes + num;
}else return num;
}
if you want to lpad some 0 onto 1.23 you can do the following
var value = 1.23
value = ("0000000"+ value).slice(-7);
Change the -7 to be whatever you want the total string length including the decimal point to be.
Added after question edit
The above should handle your question pre-edit but for the rest of it you'll need something like this.
var formatNum = function (num, preLen, postLen) {
var value = num.split("."),
padstring = "0";
padLen = (preLen > postLen)?preLen:postLen;
for (i = 0; i < padLen; i++) {
padstring += padstring;
}
if (typeof(value[1]) === "undefined") {
value[1] = "0";
}
return ((padstring + value[0]).slice(-preLen)+ "." + (value[1] + padstring).substring(0,postLen));
}
This takes the number you want formatted and the lengths you want each string to be on either side of the '.'. It also handles the case of an integer.
If you want it to output any other cases such as returning an integer, you'll have to add that in.
Try to use a string, like "000" + some value

Is checking a string against a number good style?

Which one of these to JS snippets are better in terms of style?
var answer = Number(prompt('What is the value of 2 + 2?'));
if (answer === 4) {
// do something
}
vs.
var answer = prompt('What is the value of 2 + 2?');
if (answer == 4) {
// do something
}
I'd say the first one is better because it is more explicit (and no type coercion will happen).
They are both wrong, because you should use parseInt(XX, 10) for this. And remember, every time you use == Jesus kills a puppy. So always use ===, and therefore: always check against the correct type.
It depends on what you want to do with answer. If the only thing you want to do is compare it, you don't need to convert the type:
var answer = prompt('What is the value of 2 + 2?');
if (answer === "4") {
// do something
}
If you want to end up with a number for comparison and then further processing, Number or the unary plus operator + will convert the output string to a numeric value, or NaN if it is not a valid base 10 number.
var answer = +prompt('What is the value of 2 + 2?');
if (answer === 4) {
// do something
}
There is a difference between parseInt(x, 10) and Number(x) - the former will ignore non-numeric characters at the end.
parseInt("4Hello World"); // 4
Number("4Hello World"); //NaN
+"4Hello World"; //NaN
Well of course the first one because, as you mentioned, no type coercion happens.but you should use parseInt:
var answer = parseInt((prompt('What is the value of 2 + 2?'), 10)) ;
Better would be
var n = prompt("What is the value of 2 + 2?");
n = parseInt(n, 10);
//and check

Regex for 1-10 in javascript for validation

What would be the regex for numbers ranging 1-10 and 1-5? Please help this troubled soul.
You could achive that with easy number checks in javascript:
// Convert input to integer just to be sure
mynum = parseInt(mynum, 10);
// Check number-range
if(mynum >= 1 && mynum <=10)
and
if(mynum >= 1 && mynum <=5)
If you really want to use regex:
/^([1-9]|10)$/
and
/^[1-5]$/
UPDATE:
Fixed the first regex to correctly match the string boundings
Added parseInt to the first example to ensure correct number-checks
This is not a good use of Regular Expressions.
Use simple conditions:
if (x > 0 && x < 6) {
// x is 1 - 5
}
if (x > 0 && x < 10) {
// x is 1 - 10
}
For 1-5 you only need to enclose it as character class:
/^[1-5]$/
For 1-10 you'd just need an additional alternative:
/^([1-9]|10)$/
Is there a reason you want to use regular expressions?
/([1-9]|10)/
Use numeric comparison. The following Number extension can check if a number falls between 2 values:
Number.prototype.between =
function(lower,upper, includeBoundaries){
lower = Number(lower);
upper = Number(upper);
noCando = isNaN(lower) ||
isNaN(upper) ||
lower>=upper;
if ( noCando ) {
throw 'wrong arguments or out of range';
}
return includeBoundaries
? this >= lower && this <= upper
: this > lower && this < upper
};
// usage:
(12).between(1,12); /=> false
(12).between(1,12,true); /=> true
(12).between(0,15,true); /=> true
(0).between(-5,1); //=> true
The function converts the parameters to Number because 0 can evaluate to a boolean in javascript, to be able to check if the paramaters are real number values and to be able to check if lower is not greater than/equal to upper. In those cases an error is thrown.
The includeBoundaries parameter also checks if a Number is equal to lower or upper, if it's not supplied, the function returns a real 'between'-check.
For 1-10 it can be
/^([1-9]|10)$/
and for 1-5 simply
/^[1-5]$/
The answer would be
/^([1-9]|10)$/

Categories