What does "<+" mean in this code? [duplicate] - javascript

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 5 years ago.
I encountered this strange supposed operator and am having trouble figuring out what it is. Any ideas?
var laugh = function(num){
var string="";
for (i=0; i<+num; i++) {
string+="ha";
}
return string + "!";
};
console.log(laugh(10));

One of the purposes of the + sign in JS is to parse the right part into the number.
const str = '4';
console.log(str + 5); // Concatenared as strings
console.log(+str + 5); // Sums the numbers
In your case you have an statement i < +num, which just parses num into number and i compares with it. If your num is a number, this will do nothing.
Look. I have used '10' instead of 10 and it still works, because the given string is parsed into number.
var laugh = function(num) {
var string="";
for (var i = 0; i < +num; i++) {
string+="ha";
}
return string + "!";
};
console.log(laugh('10'));

<+ is not an operator. You may interpret it simply as for (i=0; i < +num; i++) where + is the unary plus operator. The unary plus operator will coerce num into a number.
For example, if the value passed to num was "100" (as a String), the unary plus operator would coerce it to 100 (a Number).
MDN contains some examples of unary plus and other arithmetic operators.

This is the way this is parsed;
i < +num
In other words, num is being coerced to an integer before < is run on it.
There is no <+. They are parsed as separate symbols.

Related

Incorrect result while adding with parseFloat in Javascript

I want to perform addition of floating point numbers. I will always have always have only 2 decimal places.
However if I do:
var num = 0;
num += parseFloat("2434545.64").toFixed(2);
num += parseFloat("454560.91").toFixed(2);
I get the value as 02434545.64454560.91
It is appending instead of adding. Also will the addition be accurate always?
toFixed() return a String.
So you concatenate two String.
You should use toFixed() only in the last statement and you should not mix this invocation with a += operator in a even statement because here :
num += parseFloat("2434545.64").toFixed(2);
parseFloat("2434545.64").toFixed(2) is evaluated first.
It produces a String.
Then its num += String result is evaluated.
So, it would concatenate a Float with a String. Which produces again a String concatenation and not an arithmetic operation.
Just invoke toFixed() in a distinct statement :
var num = 0;
num += parseFloat("2434545.64");
num += parseFloat("454560.91");
num = num.toFixed(2);
Here you go with the solution
var num = 0;
num += 2434545.64;
num += 454560.91;
console.log(parseFloat(num).toFixed(2));
Here is the documentation for parseFloat https://www.w3schools.com/jsref/jsref_parsefloat.asp

How to convert hex to decimal WITH A LOOP in JavaScript

Is it possible to convert a hex number to a decimal number with a loop?
Example: input "FE" output "254"
I looked at those questions :
How to convert decimal to hex in JavaScript?
Writing a function to convert hex to decimal
Writing a function to convert hex to decimal
Writing a function to convert hex to decimal
How to convert hex to decimal in R
How to convert hex to decimal in c#.net?
And a few more that were not related to JS or loops. I searched for a solution in other languages too in case that I find a way to do it,but I didn't. The first one was the most useful one. Maybe I can devide by 16,compare the result to preset values and print the result, but I want to try with loops. How can I do it?
Maybe you are looking for something like this, knowing that it can be done with a oneliner (with parseInt)?
function hexToDec(hex) {
var result = 0, digitValue;
hex = hex.toLowerCase();
for (var i = 0; i < hex.length; i++) {
digitValue = '0123456789abcdef'.indexOf(hex[i]);
result = result * 16 + digitValue;
}
return result;
}
console.log(hexToDec('FE'));
Alternative
Maybe you want to have a go at using reduce, and ES6 arrow functions:
function hexToDec(hex) {
return hex.toLowerCase().split('').reduce( (result, ch) =>
result * 16 + '0123456789abcdefgh'.indexOf(ch), 0);
}
console.log(hexToDec('FE'));
Just another way to do it...
// The purpose of the function is to convert Hex to Decimal.
// This is done by adding each of the converted values.
function hextoDec(val) {
// Reversed the order because the added values need to 16^i for each value since 'F' is position 1 and 'E' is position 0
var hex = val.split('').reverse().join('');
// Set the Decimal variable as a integer
var dec = 0;
// Loop through the length of the hex to iterate through each character
for (i = 0; i < hex.length; i++) {
// Obtain the numeric value of the character A=10 B=11 and so on..
// you could also change this to var conv = parseInt(hex[i], 16) instead
var conv = '0123456789ABCDEF'.indexOf(hex[i]);
// Calculation performed is the converted value * (16^i) based on the position of the character
// This is then added to the original dec variable. 'FE' for example
// in Reverse order [E] = (14 * (16 ^ 0)) + [F] = (15 * (16 ^ 1))
dec += conv * Math.pow(16, i);
}
// Returns the added decimal value
return dec;
}
console.log(hextoDec('FE'));
Sorry that was backwards, and I can't find where to edit answer, so here is corrected answer:
function doit(hex) {
var num = 0;
for(var x=0;x<hex.length;x++) {
var hexdigit = parseInt(hex[x],16);
num = (num << 4) | hexdigit;
}
return num;
}
If you want to loop over every hex digit, then just loop from end to beginning, shifting each digit 4 bits to the left as you add them (each hex digit is four bits long):
function doit(hex) {
var num = 0;
for(var x=0;x<hex.length;x++) {
var hexdigit = parseInt(hex[x],16);
num = (num << 4) | hexdigit;
}
return num;
}
JavaScript can natively count in hex. I'm finding out the hard way that, in a loop, it converts hex to decimal, so for your purposes, this is great.
prepend your hex with 0x , and you can directly write a for loop.
For example, I wanted get an array of hex values for these unicode characters, but I am by default getting an array of decimal values.
Here's sample code that is converting unicode hex to dec
var arrayOfEmojis = [];
// my range here is in hex format
for (var i=0x1F600; i < 0x1F64F; i++) {
arrayOfEmojis.push('\\u{' + i + '}');
}
console.log(arrayOfEmojis.toString()); // this outputs an array of decimals

Spliting the binary string in half

I am trying to split binary number in half and then just add 4 zeroes.
For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000.
Can you help me with this?
Use substring to split and then looping to pad
var str = '10111101';
var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
output += "0";
}
alert(output)
try this (one-liner)
var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);
sample output
['10111101','10110000']
I guess you are using JavaScript...
"10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like:
// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
var count;
for (count = 0; count < 32; count ++) {
if (word & (1 << (31 - count))) {
break;
}
}
return count;
}
function zeroBottomHalf (num) {
var digits = 32 - nlz32(num); // count # of digits in num
var half = Math.floor(digits / 2);// how many to set to 0
var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111
var upperMask = ~lowerMask //mask for upper bits: 0b11110000
return num & upperMask;
}
var before = 0b10111101;
var after = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after = ', after.toString(2)); // outputs: 10110000
In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply:
console.log((0b10111101 & 0b11110000).toString(2))
// 10110000

convert a JavaScript string variable to decimal/money

How can we convert a JavaScript string variable to decimal?
Is there a function such as:
parseInt(document.getElementById(amtid4).innerHTML)
Yes -- parseFloat.
parseFloat(document.getElementById(amtid4).innerHTML);
For formatting numbers, use toFixed:
var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);
num is now a string with the number formatted with two decimal places.
You can also use the Number constructor/function (no need for a radix and usable for both integers and floats):
Number('09'); /=> 9
Number('09.0987'); /=> 9.0987
Alternatively like Andy E said in the comments you can use + for conversion
+'09'; /=> 9
+'09.0987'; /=> 9.0987
var formatter = new Intl.NumberFormat("ru", {
style: "currency",
currency: "GBP"
});
alert( formatter.format(1234.5) ); // 1 234,5 £
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
This works:
var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);
An easy short hand way would be to use +x
It keeps the sign intact as well as the decimal numbers.
The other alternative is to use parseFloat(x).
Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.
It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.
I made a little helper function to do this and catch all malformed data
const convertToPounds = (str = "", asNumber = false) => {
let num = Number.parseFloat(str);
if (isNaN(num) || num < 0) num = 0;
if (asNumber) return Math.round(num * 1e2) / 1e2
return num.toFixed(2);
};
Demo is here
Prefix + could be used to convert a string form of a number to a number (say "009" to 9)
const myNum = +"009"; // 9
But be careful if you want to SUM 2 or more number strings into one number.
const myNum = "001" + "009"; // "001009" (NOT 10)
const myNum = +"001" + +"009"; // 10
Alternatively you can do
const myNum = Number("001") + Number("009"); // 10

Why does NOT adding a '+ ""' after a mathematical operation in javascript make the counting of the new variables length undefined?

I'm counting the number of hours and then subtracting it by 12 if it goes above 12 (so that 1pm doesn't appear as 13pm). Below is part of my javascript code.
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12 + "";
}
Later in the code, when I'm trying count the length of the array variable 'hours[0]', it appears as unknown if I have this code instead:
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12;
}
and I don't understand why. Could someone help me out please?
The subtraction hours[0] - 12 returns a number, no matter if hours[0] contains a number or a string containing a number, e.g. "13". Adding the + "" converts the result of the subtraction to a string. A number has no length in javascript, and therefore invoking the length member of a number will return undefined.
If you add "" to an expression you're converting the resulto to a string and strings have a .length property. Numbers instead do not have a .length so what you're experiencing is normal...
var x = 42; // this is a number
var y = x + ""; // y is a string ("42")
var z1 = x.length; // this is undefined (numbers have no length)
var z2 = y.length; // this is the lenght of a string (2 in this case)

Categories