This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
JavaScript:
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
Console in browser returns: adding3+0=30
Im debugging a loop that interpolates two numbers. It works fine until addThis (the amount that needs to be added to the original number) is exactly 3 and p1 (the original value) is 0.
Every time the difference(addThis) has no decimals a wrong calculation happens.
So same problem at:
adding6+0=60 ...or at..
adding9+0=90
...all cases in between work fine (e.g. console returns: adding3.5999999999999996+0=3.59999999999999960)
Dose it 'forget' the point?
Dose it treat those values as strings?
I can't share the whole code but the problem has to be in this simple calculation right?
Thanks a lot for your thoughts and knowledge! ;)
3+0=30. It seems like it must be the string (at least anyone variable is string). You can re-visit the lines where those variable values are initialized/changed. Else you can use like the below:
addThis=Number(addThis); p1=Number(p1);
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
If you want to convert the strings to integers you can use the parseInt function:
addThis = '3'
p1 = '0'
console.log('adding' + addThis + '+' + p1 +'=' + (parseInt(addThis) + parseInt(p1)))
Related
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 2 years ago.
I successfully solved the "One Decremented" challenge on Coderbyte, but am wondering why one solution works and the alternative that I tried doesn't. the challenge is to have the function count how many times a digit appears that is exactly one less than the previous digit. (ie: '56' should return 0; '9876541110' should return 6)
This solution works (it logs 6):
var str = '9876541110'
function oneDecremented(str) {
var split = str.split('')
var total = 0
for(let i = 0; i < split.length; i++) {
if(split[i+1] == (split[i] - 1)){
total += 1
} else {}
}
console.log(total)
}
oneDecremented(str)
But if I change the first if statement to the below, the function logs an incorrect 0 for any entry:
if(split[i] == (split[i+1] + 1))
Would anyone be able to help me understand why that is? I'm sure it's a very basic answer that I'm somehow missing...
So your mistake here, and it's a very common mistake, is that you are mixing up addition with string concatenation.
When you do this:
if(split[i] == (split[i+1] + 1))
You are comparing, for example 9 with 8 + 1. But 8 isn't a number, it's a string. And when Javascript sees a string followed by the + operator, it does string concatenation. So instead of comparing 9 with 9, you are comparing 9 with 81
This doesn't happen with the - example because the - operator doesn't work on strings. So Javascript automatically converts both strings to numbers for you and does the subtraction as expected
One kinda goofy way to fix it would be to do this:
if(split[i] == (+split[i+1] + 1))
Putting a + before the string split[i+1] will force javascript to treat split[i+1] as a number because there isn't a unitary string + operator. Do note, however, this adds nothing to the readability of your code and you really might be better served using the - version instead.
The if statement if(split[i] == (split[i+1] + 1)) can also work after some minor changes.
First, as your array split[] is an array of characters, the part where you do split[i+1] + 1 can return an expected result because it will concatenate since, at first, you are trying to increment a character.
To solve this, you could just convert the string elements to integers when making the comparisons, for example:
if(parseInt(split[i]) === parseInt(split[i+1])+1) {...}
I would also avoid using == and use === instead, since === doesn't do type coercion. I hope this answer helps.
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);
This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 6 years ago.
I need to make it so that rather than 1+1=11 my code will return 1+1=2
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [];
for (var i = 0; i < 7; i++) {
arr.push(prompt('Enter GTIN Digit ' + (i+1)));
}
alert('Full GTIN: ' + (arr [0]*3)+(+ arr [2]*3)+(arr [4]*3)+(arr [6]*3) + (arr [1])+(arr [3])+ (arr [5]) );
</script>
</body>
</html>
Just one character you need to add: a + (unitary plus) before the prompt:
arr.push(+prompt('Enter GTIN Digit ' + (i+1)));
This will do the conversion.
Secondly, you need to avoid converting it back to string in your alert. Put the whole calculation between brackets or else the first string will make all the + act as string concatenation:
alert('Full GTIN: ' + (arr[0]*3+arr[2]*3+arr[4]*3+arr[6]*3+arr[1]+arr[3]+arr[5]));
Or, using a reduce:
alert('Full GTIN: ' + arr.reduce((s, d, i) => s+(i%2?d:d*3), 0));
Convert the array
The unitary + solution seems the best to me, but if -- like you put in the title -- you really want to first build the array of strings and then convert the values, then use this statement:
arr = arr.map(Number);
Remarks
It is not user-friendly to ask repeated input via prompt. The user cannot interrupt that sequence or go back. Better is to use the input element with the number type.
You would need to validate the input. As soon as you have a NaN instead of a number, or the input consists of multiple digits instead of one, the calculation cannot work correctly, and so there is no use to finish the whole input cycle.
Use parseInt()
parseInt(1)+parseInt(1)
This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 7 years ago.
Im trying to round a number to 2 decimal place. I have tried the following but not having any luck? Can somebody please help me and tell me where im going wrong??
var winPercentage = totalWins/(totalWins+totalLost)*100;
winPercentage.toFixed(2);
document.getElementById('win-percentage').innerHTML = winPercentage + " %";
i search and tried this but to be honest i have no idea what it is?
var winPercentage = totalWins/(totalWins+totalLost)*100;
expr {double(round(100*winPercentage))/100}
document.getElementById('win-percentage').innerHTML = winPercentage + " %";
Try to use the following syntax instead and alter it to your needs
var num = 5.1;
num.toFixed(2); //will become 5.10
You had the right idea with toFixed(2). The problem is that it returns the formatted number, it does not alter the variable it was called on. In other words, you just need to assign it back the the variable you were using:
winPercentage = winPercentage.toFixed(2);
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
Global.alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront));
The code above outputs something like:
base: 15000, upfront: 36, both: 1500036
Why is it joining the two numbers instead of adding them up?
I eventually want to set the value of another field to this amount using this:
mainPanel.feesPanel.initialLoanAmount.setValue(Ext.util.Format.number((base + upfront), '$0,000.00'));
And when I try that, it turns the number into the millions instead of 15,036.00. Why?
Simple example:
1 +1 == 2
"1"+1 == "11"
"1"*1 + 1 == 2
Ways to turn a string into a number:
parseInt(str)
parseInt(str,10)
parseFloat(str)
+str
str*1
str-0
str<<0
Number(str)
And here are some of the consequences:
(source: phrogz.net)
Number(str) has the same behavior as str*1, but requires a function call.
I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.
You can test the performance of these in your browser at my example page.
This might happen because they are strings. Try parsing them:
Global.alert(
"base: " + base + ", upfront: " + upfront + ", both: " +
(parseInt(base) + parseInt(upfront))
);
If those numbers are decimal you will need the parseFloat method instead.
Try
Global.alert(
"base: " + base + ", upfront: " + upfront + ", both: " +
(parseInt(base,10) + parseInt(upfront,10))
);
The 10 specifies base 10, otherwise the chance of the value being parsed as octal exists.
http://jsperf.com/number-vs-parseint-vs-plus/3
That might also be of interest to you.
It is just a performance comparison of the methods already mentioned here.
I don't know why the brackets aren't helping you out.
If I try
var base = 500;
var upfront = 100;
alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront))
I do get 600 as the answer, so it could be there is something going on in the Global.alert function?
One of the mistakes of the language design is that + is both an addition operator and a concatenation operator. Coupled with the fact that it is loosely typed and will cast implicitly means that it can give you some nasty surprises unless you take steps to ensure that you really are adding numbers and not concatenating strings. In this case, it is treating your base + upfront as strings and therefore concatenating.
Anyway, the way around it could be to have (base - upfront*-1) instead.
It's handling it as a string. You need to do your math before the string. Example:
base + upfront + ' string'
would return "15036 string".
string + base + upfront
would return string 1500036 as you are seeing now.
Or use parseInt().