JS how to add instead of concatenate numbers [duplicate] - javascript

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);

Related

How come the following code doesn't change the retrieved letters into upper case? [duplicate]

This question already has answers here:
The .replace() method does change the string in place [duplicate]
(3 answers)
Replace method doesn't work
(4 answers)
Closed 23 days ago.
The goal of this was to change the retrieved letters into upper case. I know this works if I stored lines 6 and 7 inside a variable then replace the letters inside the variable called string, but I wanted to know why this code doesn't work instead.
JavaScript strings are not mutable, meaning you can't change the value of a character at a certain index. You'll need to make a new string made of these values.
let string = 'lowercasestring'; // Creates a variable and stores a string.
let letterOne = string.indexOf('l'); // Should store as 0.
let letterTwo = string.indexOf('s'); // Should store as 7.
// mutiple lines for readability
string = string[letterOne].toUpperCase() +
string.slice(letterOne + 1, letterTwo) +
string[letterTwo].toUpperCase() +
string.slice(letterTwo + 1);
console.log(string);
Output:
"LowercaSestring"

Weird add many Char in javascript [duplicate]

This question already has answers here:
Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?
(8 answers)
Closed 3 years ago.
Today i saw an example of JavaScript and i can not understand it.
('b' + 'a' + + 'a' + 'a').toLowerCase()
result: "banana"
I don't understand it, why JavaScript add 2 'n' between each 'a'?
The first ‘b’ and ‘a’ are simply strings being added as ‘ba’. After the second ‘a’, you see a double plus sign(+), the first one is for concatenation like the previous plus sign. But the second plus sign is called the unary operator which simply transforms the string into a number, if it isn’t already. Since ‘a’ cannot be converted to a number it is converted to ‘NaN’. The final ‘a’ is added to this ‘baNaN’ string and the final ‘baNaNa’ string is made. And to finish it up, the toLowerCase function is used and the output ‘banana’ is received.

Adding two big numbers in javascript [duplicate]

This question already has answers here:
How to deal with big numbers in javascript [duplicate]
(3 answers)
Closed 3 years ago.
I've been trying to add the following numbers using javascript;
76561197960265728 + 912447736
Sadly, because of rounding in javascript it will not get the correct number, I need the number as a string.
I've tried removing the last few digits using substr and then adding the two numbers together and then putting the two strings together, sadly this doesn't work if the first of the number is a 1.
function steamid(tradelink){
var numbers = parseInt(tradelink.split('?partner=')[1].split('&')[0]),
base = '76561197960265728';
var number = parseInt(base.substr(-(numbers.toString().length + 1))) + numbers;
steamid = //put back together
}
steamid('https://steamcommunity.com/tradeoffer/new/?partner=912447736&token=qJD0Oui2');
Expected:
76561198872713464
For doing operations with such big integers, you should use BigInt, it will correctly operate on integers bigger than 2ˆ53 (which is the largest size that normal Number can support on JS
const sum = BigInt(76561197960265728) + BigInt(912447736);
console.log(sum.toString());
Edit 2020: This API still not widely supported by some browsers, so you may need to have a polyfill, please check this library

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;

Simple Javascript syntax behaving unexpectedly [duplicate]

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().

Categories

Resources