Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any downsides in casting string-integer to integer in Javascript with ( 1*x )?

if you compare different explicit methods of type-casting a variable to integer:

var y = parseInt(x,10) + 'text'; // too long, needs wrapping, needs anti-octal hack

var y = x.toFixed(0) + 'text'; // still long, and even uglier, and maybe buggy

var y = Math.floor(x) + 'text'; // long and uses Math object

var y = Number(x) + 'text'; // long

var y = +x + 'text'; // very short, but too hacky

var y = 1 * x + 'text'; // simple and short

You will see, why the last one is my favourite. Yet, i wonder, if there are any hidden issues with this method ?

like image 491
c69 Avatar asked Nov 27 '25 13:11

c69


1 Answers

The last one does work:

1 * 0.5; // 0.5

if you want the best readiblilty use parseInt. And the radix is not a hack!

Edit:

My favorite:

var y = x|0 + 'text';


Edit: Please do note that this "trick" only works with 32-bit signed integers. Because that's JavaScript's implementation of it's bit logic. So the largest positive number you can use this for is 2147483647.

There is one unsigned bit operation, unsigned right shift. 0 >>> 1

like image 69
Joe Avatar answered Nov 29 '25 01:11

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!