Simple Javascript syntax behaving unexpectedly [duplicate] - javascript

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 8 years ago.
It is showing 60 + 5 as 605 instead of 65
g = document.getElementById("height1").value * 12;
alert(g); <---- This is showing 60
h = document.getElementById("height2").value;
alert(h); <---- This is showing 5
b = g+h;
alert(b); <---- This is showing 605
Any ideas

Javacript is not a strongly typed language. It does it's best to interpret the type of variables and generally, if you try to add a string-like variable to an integer-like variable, it will interpret it as string concatenation.
You could force the variables to be interpreted as integers like this:
b = parseInt(g) + parseInt(h);
Or, using other tricks that will force the variable to become numeric, like this:
b = (g*1) + (h*1);

Use parseInt() to convert to integer. + in Javascript is both for adding and concatenation.

how about b = (g+h)?
make sure the vars are integers, else convert them to integers

If the values of those HTML elements are strings (like in text input boxes?) then what you're doing is concatenating strings, not adding numbers.
You need to 1) be sure the input values are actually numeric, and 2) convert the string to an integer using parseInt().

Related

Why does summation of string and number output a string but multiplication of them output a number in javascript? [duplicate]

This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed last year.
string + number
const a = "5";
const b = 7;
console.log(a + b);
Output is -
57
string * number
const a = "5";
const b = 7;
console.log(a * b);
Output is -
35
it's based on what the creators of JS thought would be more useful. In every other language you can concatenate the strings, numbers and other stuff using the +. So in JS they thought that would be a nice solution as well. But then... what does it mean to multiply a string? The creators of JS had no answer, so assumed this must be a mathematical operation.

Is there a better way to achieve this? '000000'.slice(0, -'434'.length) + '434' = '000434' [duplicate]

This question already has answers here:
convert '1' to '0001' in JavaScript [duplicate]
(4 answers)
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 3 years ago.
Yep, the title says pretty much everything. Basically I want a default X-digit number which is all zeros. Then, from this number, I want to replace the last characters with other numbers. For example, if I have '434', and the default is '000000', the result should be '000434'.
In Ruby, this is the equivalent of doing '%.6d' % 434 and it returns '000434'. If the number I want to save has more than 6 digits, I just use that number instead. I realized that as I'm working with strings I could use this solution:
let base = '000000'
let str = '434'
console.log(base.slice(0, -str.length) + str)
Buuut, even if it's a simple approach, I don't know if it's the best. What daya' think?
For compatibility with older JS environments, you can depend only on a simpler slice:
(base + str).slice(-6)
For modern ones, padStart is available:
str.padStart(6, '0') // or String(num)
JavaScript has string.padStart(length, padString)
let str = '434'
const updated = str.padStart(6, '0')
console.log(updated)

How do I convert my HEX string into a number? [duplicate]

This question already has answers here:
How to convert decimal to hexadecimal in JavaScript
(30 answers)
Closed 3 years ago.
I wish to convert the whiteHex variable to a decimal using the parseInt() function, and store it in a variable, whiteDecimal.
var whiteHex = 'ffffff';
var whiteDecimal = parseInt(whiteHex);
I am unsure if the above is correct or not. The reason being, that I then wish to subtract 1 from whiteDecimal and store it in a variable offWhiteDecimal. This is where I am getting stuck. How can I subtract one from the ffffff hex value? Am I missing something within the parseInt function?
You're looking for this:
var whiteDecimal = parseInt(whiteHex, 16)
console.log(whiteDecimal - 1);
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Syntax

JS how to add instead of concatenate numbers [duplicate]

This question already has answers here:
Javascript variables not adding two variables correctly, only concatenating
(3 answers)
Closed 4 years ago.
This question has an answer:
see - Javascript variables not adding two variables correctly, only concatenating
I am trying to add 5 units to a number but the number is being concatenated instead.
this.graphicState[i].shapes[j][k].x += 5
Each time this is run in a loop the outputs are
105.00
105.005
105.0055
105.00555
...
The output I am looking for is,
105.00
110.00
115.00
120.00
...
I tried,
this.graphicState[i].shapes[j][k].x += parseFloat(5)
I also tried this, but get the same results,
this.graphicState[i].shapes[j][k].x = this.graphicState[i].shapes[j][k].x + 5
Thanks,
You need to convert any/all string values to numbers in an expression that has strings as operands with + as the operator. The 5 isn't the issue, this is:
this.graphicState[i].shapes[j][k].x
So, that's what needs to be converted. You can do that easily by prepending a + to it:
+this.graphicState[i].shapes[j][k].x;
Do the conversion on the string first and then use the converted value in your mathematical expression. Here's a simplified example:
var result = "5"
result = +result + 10;
console.log(result);
Try this method
this.graphicState[i].shapes[j][k].x = (parseFloat(this.graphicState[i].shapes[j][k].x) + 5).toFixed(2);

How to sum two different functions in javascript [duplicate]

This question already has answers here:
Javascript numbers concatenate instead of adding but typeof is number not string
(5 answers)
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
I have different functions which return values; So i created different function to sum both values.
function result(){
var result = firstFunct() + secondFunct();
alert(result);
return result;
}
And it gives for me a result like joint of two strings: 1010 instead 20. What kind of operator do I need to use two sum both of them?
This is most probably because your functions are returning string and not a numeric data type. You will need to cast the output of the functions
var result = Number(firstFunct()) + Number(secondFunct());
Note, casting to a number could also be done in a shorter way, using the + operator:
var result = (+firstFunct()) + (+secondFunct());
To cast to a numeric you can also do:
var num = 1 * numericstring;

Categories

Resources