-2

in typescript, as the number type can be int or float, so what if I use number type with bit operations

I have see some library use this

const a = 1.23
const b = a | 0

Sorry for the inaccurate expression, I'm just curious about this feature and not actually applying it. If I think about it from a memory perspective, like in C++, If I use

a |= 0

I can convert a into its binary form, Each bit is ORed with 0 and get the result. But what's the memory struct in Js, If a = 1.23, what's the binary form, and why the ORed will like a trunc operation?

and the result of b is 1, so can I use this method as a method of taking integers

I think I found the answer here: https://stackoverflow.com/a/52650645/28235582

3
  • Who's going to stop you? Commented Nov 14, 2024 at 13:39
  • • Welcome to Stack Overflow! "the number type can be int or float" No, the number type in TypeScript is the same as in JavaScript, which is effectively the same as double in languages with such types. Please edit to fix this. • What do you mean "method of taking integers"? Yes, b will always be some integer in the range of –2147483648 through 2147483647; like some kind of rounding and modulo. Is that really what you want? What should 1e20 become? Commented Nov 14, 2024 at 13:51
  • TS is no different from JS in this respect (there are no type errors or anything) so this is effectively a duplicate of the linked q/a above. See that for more information. You should use Math.trunc() instead of | 0 unless you have a use case that compels otherwise. Commented Nov 14, 2024 at 14:01

1 Answer 1

0

Yes, you can use bitwise operations in TypeScript as a method of converting floating-point numbers to integers! The bitwise OR operation (| 0) is commonly used to truncate a floating-point number to an integer.

Sign up to request clarification or add additional context in comments.

2 Comments

"The bitwise OR operation (| 0) is commonly used to truncate a floating-point number to an integer." Is it? In JavaScript? I suppose if you already know the range of your numbers is confined to the 32 bit integers, but why not just use Math.trunc()?
Why "The bitwise OR operation (| 0) is commonly used to truncate a floating-point number to an integer"? I always thought that the OR operation was done on every bit. Is this a feature of JS or is this the case for all OR operations?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.