views:

198

answers:

4
A: 

It's been a while since I've done any C/C++, so I'm not quite sure what is happening with *((int*)&a);. However, to answer your last question, decimal to integer conversion is as simple as ~~3.145 since bitwise operators in JavaScript convert everything to 32bit integers.

Justin Johnson
I'd love to know what the down vote is for
Justin Johnson
wasn't me, but ~~x is twice as slow (testing on Chrome) as x|0 or x<<0, and either way, OP isn't asking not for math.floor(x), but a reinterpret_cast.
Jimmy
The OP specifically asked "How on earth can I translate between and int and a float in javascript?" Although not the only method, what I provided is the closest equivalent in JavaScript to address float to int conversion
Justin Johnson
Also, in FF 3.5.6 on OS X 10.5.8, `~~` is faster than both `|` and `<<`, but the margins is smaller. From the average of 4 test over 1000000 iterations, they performed as follows in a cursory benchmark: `Math.floor` 2270ms, `~~` 1770.25ms, `|` 1774.5ms, `>>` 1783ms.
Justin Johnson
+4  A: 

You certainly don't get anything low-level like that in JavaScript. It would be extremely dangerous to allow recasting and pointer-frobbing in a language that has to be safe for untrusted potential-attacker web sites to use.

If you want to get a 32-bit IEEE754 representation of a single-precision value in a Number (which remember is not an int either; the only number type you get in JavaScript is double), you will have to make it yourself by fiddling the sign, exponent and mantissa bits together. There's example code here.

bobince
+1  A: 

There are some functions to implement conversion here. The solution is quite slow however, and you may wish to consider a redesign.

Joel Potter
A: 

Like the other posters have said, JavaScript is loose typed, so there is no differentiation in data types from float to int or vice versa.

However, what you're looking for is

float to int:

Math.floor( 3.9 ); // result: 3 (truncate everything past .) or
Math.round( 3.9 ); // result: 4 (round to nearest whole number)

Depending on which you'd like. In C/C++ it would essentially be using Math.floor to convert to integer from float.

int to float:

var a = 10;
a.toFixed( 3 ); // result: 10.000
Dan Beam
Double bitwise-not (`~~`) is considerably faster than `Math.floor`. Over 1,000,000 iterations, `~~val` (1829ms) is an average of 455ms faster than `Math.floor(val)` (2284ms).
Justin Johnson
so per iteration you're picking up 0.000000455 of a second, cool story bro
Dan Beam