How can I concatenate arithmetic and strings? - javascript

So javascript uses the plus operator to concatenate strings with strings and/or integers like so:
<script>document.write("One plus Two equals " + 3);</script>
<script>document.write("One plus Two equals " + "three");</script>
At least I think it does :/ --Because of this, things get confusing if I wanted to concatenate integers and/or strings with arithmetic. I shall try here anyway. don't laugh :(
<script>document.write("One plus Two equals " + 1+2);</script>?
I wonder, could the solution as easy as adding moar parentheses?!
<script>document.write("One plus Two equals " + (1+2));</script>
Am I way off base here?

Related

Why '+' act like a parse in javascript when converting from string to float or integer and how it differs regarding on performance?

parseFloat("10.1") + parseFloat("32.3")
vs
+ "10.1" + + "32.3"
both statement will produce the same result 42.4
using this statement:
+ "10.1" + + "32.3"
Why does + act like a parse and how each statement affects the performance in the program?
JavaScript uses implicit conversions. The unary + only accepts numbers, so, when you give it a string, it converts it into a number. JavaScript does this by parsing the string as a number. Since JavaScript doesn't have an integer type, it is always parsed as a floating point number.
To answer the performance question: jsperf.
From my tests, the unary operator + is 8 times faster than parseFloat.
I'd guess this has to do with the expense of function calls in JS, etc.

Javascript: concatenation with "," doesn't work

<button onclick="rzut()" />
<div id="wynik" />
<script type="text/javascript">
function rzut() {
document.getElementById("wynik").innerHTML = "Wynik to",Math.floor(Math.random()*6)+1;
}
</script>
For an unknown reason my script show only "Wynik to" and it skips the next part (math.floor etc)
Okay, let's go over some basics.
The first thing I would like to bring up is the concept of an Overloaded Operator. An overloaded operator, in short, is an operator that has different behaviour for different operands. An example of an overloaded operator in Javascript is +. For example:
var x = 4 + 4;
// x = 8
As you can see, adding two numeric values has the effect of summing the fields. But what about..
var x = "4" + "4";
// x = "44";
Well, because the types are strings, it behaves differently, hence it has an overloaded behaviour.
The + symbol will summate numeric values, but concatenate string values.
Bringing this forward to your example, you want to end up with a string value like..
"Wynik to,3"
Where 3 can vary. So let's look at it like this..
"Wynik to,X"
where X is some variable. Well.. this means you've got to build the string on the fly.. So following your approach (and not using some of the nice ES6 features that have been introduced), you can use our friendly overloaded + to accomplish this..
"Wynik to," + X
Where X is some random number between 1 and 6 therefore..
"Wynik to " + (Math.floor(Math.random()*6)+1);
So you'll see here, we've got a numeric value on the right hand side and a string value on the left hand side.
What Javascript does in this situation is what's known as arithmetic promotion, where all operands are promoted to the precision of the highest operand.
In this case, the right hand side of the equation is promoted to a string. Then, as we've seen above, our overloaded operator knows what to do with two strings.

Why is number + string a string in javascript?

Sort of trying out some quirks in javascript:
First I did
console.log("5" + 1);
This prints 51, this is normal right, both number and string have a + operator, but since string is the first variable it will convert 1 to a string.
Now when I did this:
console.log(1 + "5")
I expected output to be 6, as I thought it would convert string to a number.
However, the magic output was 15.
Could anyone more experienced in javascript brighten this up for me?
Quoting ECMAScript spec The Addition operator ( + ) section:
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
So the order doesn't matter here.
console.log(1 + "5")
I expected output to be 6, as I thought it would convert string to a number. ...
But then what would you expect if you had written the following?
console.log(1 + " fine day")
or
console.log(1 + " answer(s) to my question")
There can be no assurance as a general rule that a string is convertible to a number. But any number can be converted to a string. That's why the conversion rules are written to move toward a type that is compatible. (In contexts where you as a programmer know that a string can be safely converted to a number, then you can do so explicitly so that the + operation is between two numbers. But that is not true in general for strings.)
In other contexts, this is also why small ints and low precision floats would be converted to large ints or double precision floats when operating on mixed types that the latter types. You can safely convert the limited forms into the larger forms, but you cannot safely go in the other direction in general. A small int can be represented as a big int or a double, but the other direction is not generally a safe conversion.
So conversion rules for operation on mixed types are written as much as is feasible to move toward mutually compatible types that are safe common types. It is left to the programmer to write explicit conversions for the special cases where a more general type can be safely converted to a more limited type.
In both cases the value will be converted to a string.
When you add a number to a string or a string to a number, the result is a string.
Simply use parseInt(value) or toString(value) to force the conversion.
You can try code :
console.log(1 + parseInt("5"))
=> 6
Concatenation also uses + in Javascript.
var result = "String" + number + obj;
// is equivalent to
string result = "String" + number.ToString() + obj.ToString();
However thing is, in C# / .net you could do the same thing, and you will get the same result - System.Console.WriteLine("result is " + 10 + 20);.
In JavaScript (and C# for that matter) strings are immutable. They can never be changed, only replaced with other strings. You're probably aware that combined + "String" doesn't directly modify the combined variable - the operation creates a new string that is the result of concatenating the two strings together, but you must then assign that new string to the combined variable if you want it to be changed.
The argument about using mathematical operators to do string concatenation is arguably an "incorrect" argument, but there's also an argument to be made that using + to do a lot of string concatenation can be very slow.

javascript bigger than if statement not working correctly

I am no expert in javascript, so hope someone can help me out.
I have the following code, but for some reason it always thinks the statement is true
delvNum=document.getElementById("deliveryNum").value;
delvQTY=document.getElementById("delvQTY"+id).value;
orderQTY=document.getElementById("orderQTY"+id).value;
if (delvQTY>orderQTY)
{
alert("Can't deliver more than " + orderQTY + ", you are trying to deliver " + delvQTY + ". Please fix!");
document.getElementById("delvQTY"+id).focus();
return;
}
The error message does show the quantity of each var, and is correctly being passed through.
You are comparing strings and not numbers.
Use parseInt or parseFloat
if (parseFloat(delvQTY)>parseFloat(orderQTY))
or
if (parseInt(delvQTY,10)>parseInt(orderQTY,10))
You're doing a string comparison, not number comparison and, for example, "9">"1111" is true.
You need to parse your values :
if (parseFloat(delvQTY)>parseFloat(orderQTY))
See parseFloat.
You need to make sure delvQTY and orderQTY are Number before you can do > comparison.
var delvValue = parseInt(delvQTY, 10); for converting to integers.
Or for floating point numbers: var delvValue = parseFloat(delvQTY);
You're comparing the string values, rather than numerical ones. You should say:
delvNum = parseInt(document.getElementById("deliveryNum").value, 10);
(assume you are dealing with integers, else use parseFloat).
Note the 10 to say you're dealing with base 10 - without it, if someone types a leading zero then you'll get baffling results.

Adding two numbers in JavaScript incorrectly [duplicate]

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

Categories

Resources