This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I am new to javascript, and I tried to run the below in Brave browser:
'1' + '2' - 3;
The browser replied with the value 9, which I don't understand.
'1' + '2' is concatenation of strings and result is '12'.
'12' - 3 is math operation 12 - 3 and result is 9.
You shoud do the intermediate steps and see for yourself.
Try:
a = '1' + '2';
console.log(a);
b = a - 3;
console.log(b); // prints 9
The + operator is described as for purpose of sum of numeric operands or string concatenation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition
That is because your first two numbers are strings. you would get a correct answer if you used:
1 + 2 - 3
Or if you cannot avoid doing a calculation on a string, convert it to a number first:
parseInt('1') + parseInt('2') - 3
'1'+ '2' = '12' is a string but it is converted to an integer before being substracted by -3, so 12-3.
Related
This question already has answers here:
Autoconversion in javascript: Isn't it supposed to convert a string to a number when done like stringvar = 1+stringvar?
(2 answers)
Adding and subtracting strings and numbers in Javascript - auto type conversion?
(5 answers)
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 1 year ago.
Why is the last operation returning 20?
console.log(2 + 2); // equals 4
console.log("2" + "2"); // equals "22"
console.log(2 + 2 - 2); // equals 2
console.log("2" + "2" - "2"); // equals 20
+ and - evaluate left-to-right. When either operand is a string, the result is concatenation. When both are numbers, the result is addition.
In contrast, - will always coerce both sides to numbers.
'2' + '2' - '2'
does
// left-to-right
('2' + '2') - '2'
// both sides are strings, so concatenate
'22' - '2'
// operator is -, so coerce both sides to numbers
22 - 2
20
The signs + and - work very differently in string concatenation. The + operator gives direct concatenation instructions on strings whereas the - operator tries to coerce the types and perform the mathematical function.
console.log("2" + "2");
console.log(typeof ("2" + "2"));
console.log("2" - "2");
console.log(typeof("2" - "2"));
This question already has answers here:
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 4 years ago.
guys.
I'm having some issues with this function
const incrementString = str => {
if (!str.match(/[\d+]$/)){
return str += 1
} else{
return str.replace(/[\d+]$/, ch => new Number(ch) + 1)
}
}
What I'm trying to do with that function is + 1 the number at the end of the string, and if the string doesn't has one, I'll add a 1 at the end.
string expected
"foobar000" "foobar001"
"foo" "foo1"
"foobar025" "foobar026"
I don't know if it's possible to do it with replace and regex, I have in mind a solution with loops, .length, split, etc..., but I want to do it with regex, if it's possible.
Problem: How can I take the number at the end of the string, with the leading zeros, and sum them a 1?
this are some examples of the bad behavior of my function
Expected: 'foobar011', instead got: 'foobar11'
Test Passed: Value == 'foo1'
Expected: 'foobar002', instead got: 'foobar2'
Test Passed: Value == 'foobar100'
Test Passed: Value == 'foobar100'
Test Passed: Value == '1'
Thanks and happy holydays
You could store the length of the numerical string and apply after incrementing the wanted leading zeroes.
function increment(s) {
var [left, right = '0'] = s.split(/(\d*$)/),
length = right.length;
return left + (+right + 1).toString().padStart(length, '0');
}
console.log(['foobar000', 'foo', 'foobar025'].map(increment));
I used all your hints and answers to check different options to solve my problem.
Finally, I solved with the "String of numbers" and the padStart hints.
const incrementString = str => {
if (str.match(/[0-9+]+/g)) {
let numbers = str.replace(/[a-z+]+/g, "")
return str.replace(numbers, (Number(numbers) + 1 + '').padStart(numbers.length, 0))
} else {
return str + 1
}
}
I hope this helps others as it helped to me.
Thanks and happy holydays
I want to create a Roth IRA value calculator. The end result would accept values for annual contribution amount, interest rate, and total number of contribution years.
The calculation—a geometric series—that I need is:
Balance(Y) = P(1 + r)Y + c[ ((1 + r)Y + 1 - (1 + r)) / r ]
FWIW, I'm getting my math information here: http://www.moneychimp.com/articles/finworks/fmbasinv.htm
How would one go about writing this in Javascript? I've been reading about the math functions, but I can't seem to wrap my head around it...
I would definitely read up on JavaScripts operator precedence
A few things to note...
Grouping holds the highest precedence (), NOT with square brakets []
square brackets are for accessing object members and array literals.
There is no operator for exponents in JavaScript use Math.pow(x, n)
For mathematical operations, you MUST use operators 4(x + 1) with throw an
error telling you 4 is not a function. 4 * (x + 1) works.
The following operators are evaluated left-right * / % + - with * / %
holding equal precedence over + -. So mathematical operations are going to behave similar to pemdas.
Another note JavaScript is a dynamic loosely typed language. All numbers are 64-bit floating points, which can yield odd results in some math equations, e.g.
> .1 + .2 = 0.30000000000000004
Another good read
For solving any mathematics series below algorithm can be used. Even for some cases it will not satisfy your expected answer, but it will be correct in some other way.
Steps are as below:
1) Get the difference between the numbers as shown below:
2) Keep making difference until it seems same(difference get 0).
3) Put the same last number which is coming same in that sequence and by adding that difference complete the series by coming up.
<pre>
Examples are as below:
1 2 3 4 5 6 **7**
1 1 1 1 1 **1**
1 4 9 16 25 **36**
3 5 7 9 **11**
2 2 2 **2**
1 8 27 64 125 **216**
7 19 37 61 **91**
12 18 24 **30**
6 6 **6**
0 **0**
</pre>
The same above algorithm is implemented in below js code.
<pre>
//the input
var arr=[1,4,9,16];
var pa6inoArrayMelvo = function(arrr){
var nxtArr=[];
for(i=0;i<arrr.length;i++){
if(arrr[i+1] != undefined){
nxtArr.push(arrr[i+1] -arrr[i]);
}
}
return nxtArr;
}
var keepArray=[];
var keepAlltheArray= function(ar){
var tempArr=[];
keepArray.push(ar);
if(ar.length>1){
tempArr=pa6inoArrayMelvo(ar);
keepAlltheArray(tempArr);
}else{
generateArray(keepArray.length-1);
console.log("ans is:"+keepArray[0]);
}
}
var generateArray=function(idx){
if(keepArray[idx+1]){
var a=keepArray[idx+1];
var b=keepArray[idx];
var ans=a[a.length-1]+b[a.length-1];
keepArray[idx].push(ans);
}else{
var ans=keepArray[idx][keepArray[idx].length-1];
keepArray[idx].push(ans);
}
if(idx>0){
generateArray(idx-1);
}
}
keepAlltheArray(arr);
</pre>
As Yann Chabot said
P*(1 + r)*Y + c(((1 + r)*Y + 1 - (1 + r)) / r)
is the right answer but just as a side note, if you dont have P initialy you should set it to 1 by default.
This question already has answers here:
How to convert decimal to hexadecimal in JavaScript
(30 answers)
Closed 8 years ago.
I want to convert an number (integer) to a hex string
2 (0x02) to "\x02"
or
62 (0x0062) to "\x62"
How can I do that correctly?
You can use the to string method:
a = 64;
a.toString(16); // prints "40" which is the hex value
a.toString(8); // prints "100" which is the octal value
a.toString(2); // prints "1000000" which is the binary value
Well, it's seems that you want just to concatenate the integer with \x.
If so just to like that:
var number = 62;
var hexStr = '\x' + number.toString(16);
But you have something strange about explaining.
Note: that 62 is not the same as 0x62, 0x62 would be 98.
var converted = "\x" + number.toString(16)
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 9 years ago.
I can't figure out how to solve the following problem.
I have an array of numbers from 1 to 100.
I need to convert them to strings but to a length of 5.
So, for instance:
1 becomes 00001
2 becomes 00002
3 becomes 00003
4 becomes 00004
etc, etc..
It seems so easy but I cannot find a function. The best I found was .toFixed(n) which is the number of decimal points to use.
Here's a very simple padding function:
function padLeft(str, length, paddingCharacter) {
str = '' + str; //Make sure that we convert it to a string if it isn't
while (str.length < length) {
str = paddingCharacter + str; //Pad it
}
return str;
}
padLeft(123, 5, '0'); //00123