Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parseInt (1/10000000) returns 1. Why?

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?

like image 579
timaschew Avatar asked Dec 25 '14 20:12

timaschew


2 Answers

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);
}
like image 129
Niet the Dark Absol Avatar answered Oct 19 '22 16:10

Niet the Dark Absol


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
like image 21
Boann Avatar answered Oct 19 '22 14:10

Boann