Addition of two strings gives unintended result [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 3 years ago.
I would like to get a numeric value in a string which is in the format 1 111.
I used a regex to extract it:
([0-9]*)\s([0-9]*)
then I thought that I will obtain the correct result with this operation:
regex_result[1]*1000+regex_result[2]
But actually I just have to addition them and I do not understand why.
var str= "Bit rate : 5 333 kb/s"
var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);
//attempted result, but incorrect code
console.log(bitrate[1]+bitrate[2]);
//attempted correct code, but wrong result
console.log(bitrate[1]*1000+bitrate[2]);

Here, the second captured group just so happens to be 3 characters long, so multiplying the first captured group by 1000 and adding it to the second group will just so happen to produce the same result as plain concatenation.
But you have to add them together properly first. Your second attempt isn't working properly because the right-hand side of the + is a string, and a number + a string results in concatenation, not addition:
var str = "Bit rate : 5 333 kb/s"
var bitrate = str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate[1] * 1000 + Number(bitrate[2]));
If the input isn't guaranteed to have exactly 3 digits in the second capturing group, the concatenation method won't work.

You can parse them as ints instead of manipulating strings
var str= "Bit rate : 5 333 kb/s"
var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);
console.log(parseInt(bitrate[1] * 1000) + parseInt(bitrate[2]));

Related

(solved) Javascript : Cutting/Removing excess characters from a string if it exceeds the Limit

This question is a bit tricky to explain. Say i have an variable whose length is dynamic meaning it is random,i want to change its length to the first 5 or a certain amount of characters regardless of the length of the characters existing in the variable. I hope i could explain what i am trying to do
.________________________________________________________________________.
I really dont know which direction to go in or what step to take in order to reach my goal but i just copy/pasted some random code of the internet that didn't work so i did not think it is of any importance to include in this query,but i could share on demand
Pseudo code...
const str = "the string";
const start = 0;
// const end = str.length;
str.substring(start, (optional) end);
So if you want just first five characters, you do something like
str.substring(0, 5);
If it's only integers (numbers) you could simply generate a random whole number between 11111 and 99999 (so it's always 5 digits), like this:
let x = Math.floor((Math.random() * 99999) + 11111);
do you have a delimited amount of decimals? if not, you should remove Math.floor and convert into string and after that substring as in the other answer (and convert back into a Number if needed as Number). If yes, you should change the "11111" and "99999" to the length of integers needed, and use toFixed() to limit the number of decimals. –
DavidTaubmann

Convert Numbers to FULL binary octets [duplicate]

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 6 years ago.
Take this IP address:
192.168.1.1
I want to break it down into 4 full binary octets, so:
11000000 . 10101000 . 00000001 . 00000001.
All of the conversions I know, and those that I've found on other stackoverflow questions, only return the binary number itself, for example:
(1 >>> 0).toString(2) returns 1 when I want 00000001
Number(2).toString(2) returns 10 when I want 00000010
Is there an in-built javascript method that I haven't come across yet or do I need to manually add the 0's before depending on the number?
You can use Number#toString method with radix 2 for converting a Number to corresponding binary String.
var str = '192.168.1.1';
console.log(
// Split strings based on delimiter .
str.split('.')
// iterate over them
.map(function(v) {
// parse the String and convert the number to corresponding
// binary string afterwards add preceding 0's
// with help of slice method
return ('00000000' + Number(v).toString(2)).slice(-8)
// rejoin the string
}).join('.')
)
The simplest solution is to prefix the answer with zeros and then use a negative substring value to count from the right, not the left...
alert(("00000000" + (1 >>> 0).toString(2)).substr(-8));

how to evaluate this Number("2/4") in JavaScript [duplicate]

This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 7 years ago.
Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?
You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...
If you always have a fraction in format A/B, you can split it up and compute:
var s = "11/47";
var ssplit = s.split('/');
document.body.innerText = ssplit[0] / ssplit[1];
Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.
You are looking for eval. Note
parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5
function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}
Try with eval function :
eval("2/4");
Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.
So, what you can do is like this:
Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234
So, you can split string then use that like #Yeldar Kurmangaliyev answered for you.
(function(str){
var numbers = str.split("/").map(Number);
return numbers[0] / numbers[1];
})("2/4")
Keep in mind this does not check for invalid input.

(Js) number method to add a comma after the first number and remove the 2 number after comma ?? is there any? [duplicate]

This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 8 years ago.
I want to format a number to two decimal places. Say the user enters 8764444 it should be formatted as 8.76. is there some built-in function in javascript to do that?
No, there is no built in method for exactly that, but you can use the substr method to get parts of a string to do the formatting:
var input = "8764444";
input = input.substr(0, 1) + '.' + input.substr(1, 2);
// show result in Stackoverflow snippet
document.write(input);

How are JavaScript expression evaluated?

In JavaScript, can someone explain the results of the 2 following expressions:
"4" + 4 and 4 + "4"
Thanks!
Both will result in the String:
"44"
This is because the + operator serves 2 purposes -- addition and concatenation. And, if either operand is a String (or is cast to a String by the internal ToPrimitive()) they'll be concatenated.
This is described in the specification as:
7) If Type(lprim) is String or Type(rprim) is String, then
a) Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8) Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.
If you want to ensure addition, you can use parseFloat() or the unary + on each:
var a = "4", b = 4;
console.log(parseFloat(a) + parseFloat(b)); // 8;
console.log((+a) + (+b)); // 8, extra parenthesis for clarity
1+'1'+1 = '111'
1+1+'1' = '21'
'1'+(1+1) = '12'
'1'+1+1 = '111'
Javascript performs math until it hits a string and then switches to concatenation, and it also follows regular formula rules run () operations first.
they'll both be '44'. The presence of the '4' as a string casts the whole operation to a string, so the two characters are concatenated.
Cited from: http://javascript.about.com/od/variablesandoperators/a/vop10.htm
One thing that can be confusing to beginners is that JavaScript uses +
with text strings to mean something completely different from what it
means with numbers. While with numbers + means add the numbers
together with text + means concatenate them together. Concatenation
basically means joining one text string onto the end of the first so
that "my"+"book" gives "mybook" as a result. Where beginners tend to
get confused is that while 3+3 gives 6, "3"+"3" gives "33".
You can also use += with text strings to directly add the variable or
text on the right onto the end of the text string variable on the
left.
Mixing Data Types
Additional confusion can arise when you are working with variables
that are of different types. All operations require that the variables
that they are operating on both be of the same type. Before JavaScript
is able to perform any operations that involve two different data
types, it must first convert one of the variables from one type to the
other. You can't add a number to a text string without first either
converting the number to text or the text to a number.
When converting between data types we have two choices. We can allow
JavaScript to do the conversion for us automatically or we can tell
JavaScript which variable that we want to convert.
JavaScript will attempt to convert any text string into the number
equivalent when performing subtraction, multiplication, division, and
taking remainders. Your text string will actually need to contain
something that JavaScript can convert to a number (i.e., a string like
"10") in order for the conversion to work.
If we use + then this could either mean that we want to convert the
string to a number and add then or that we want to convert the number
to a string and concatenate them. JavaScript can only perform one of
these two alternatives. It always converts numbers to strings (since
that will work whether the string contains a number or not).
Here are some examples.
"5" - 3 = 2;
"5" + 3 = "53"
2 + "7" = "27"
5 + 9 + "1" = "141"
Since subtraction only works with numbers 1 converts the text string
into a number before doing the subtraction.
In 2 and 3 the number is converted to a text string before being
concatenated (joined) to the other text string.
In 4 the leftmost addition is done first. Since these are both numbers
they are actually added together and not treated as text. The result
of this first addition leaves us with a similar situation to the third
example and so the result of that addition is converted to text and
concatenated.
To actually force JavaScript to convert a text string to a number we
can use Number("3") or alternatively to force JavaScript to convert a
number to a text string we can use String(5).
Expressions in JS work on two prime principles.
B O D M A(includes concat) S
Left to right order of execution
However, its not straight forward
for + operator
as far as it encounters numbers it will do math addition using left to right execution, However,as soon as it encounters a string, it concatenates the result (that's calculated till encountering a string) with rest of the expression.
//left to right execution
console.log(10+10+"10") //2010, (10+10) of numtype + "10" of stringtype concat(20+"10")
console.log(10+10+"10"+10+10) //20101010,
//(10+10) of number type + "10" stringtype(now since a string is enc.) + (10+10) of number type would act as strings and get concatenated = 20+"10"+"1010"
console.log("10"+[10,10,10]+10) //1010,10,1010
//"10"of stringtype + array of numtypes + 10 of numtype
// "10" concats with first element of array, last number 10 concats with last element of array.
for all other operators such as -,*,/,^...
if all occurrences are numbers/numbers as string, it will do the respective math operation treating "numbers as string" to be numbers.
console.log("10"-10) //0
console.log("10"/10) //1
console.log("10"*10) //100
console.log(10+"10"*10) //110 //BODMAS
console.log(Math.pow(10,"10")) //10000000000
if there are occurrences of non-numeric strings,arrays,objects in the middle of expression that involve (-,*,/,^...)math operations, it will always return NaN
console.log(10-{id:1,name:"hey"}-10) //NaN
console.log(10-10-"hey"-10-10-10) //NaN
console.log("hey"/10) //NaN
console.log("hey"* 3) //NaN
console.log(["hey","hey"]*"3") //NaN
console.log("10"/[10,10,10]/10) //NaN

Categories