Why parseInt(1/10000000)
results 1
, when parseInt(1/1000000)
result is 0
?
I need some analog to Java's int casting like int i = -1/10000000;
, Which is 0
.
Should I use Math.floor
for positive and Math.ceil
for negative? Or is there another solution?
At first the question seems interesting. Then I looked at what 1/10000000
is.
< 1/10000000
> 1e-7
Therefore:
< parseInt("1e-7"); // note `parseInt` takes a STRING argument
> 1
If you want to truncate to an integer, you can do this:
function truncateToInteger(real) {
return real - (real % 1);
}
parseInt expects to parse a string argument, so converts it to a string first.
1/1000000
when converted to a string is "0.000001"
, parseInt then ignores everything from "." onwards, since it is for integers only, so it reads it as 0
.
1/10000000
is so small that converting it to a string uses scientific notation "1e-7"
, parseInt then ignores everything from "e" onwards, since it is for integers only, so it reads it as 1
.
Basically, parseInt is just not what you should be doing.
To convert a number to an integer, OR it with 0, since any bitwise operation in JavaScript forces the number to a 32-bit int, and ORing with 0 doesn't change the value beyond that:
>(-1/10000000)|0
0
>1234.56|0 // truncation
1234
>(2147483647+1)|0 // integer overflow
-2147483648
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With