The parseInt (1/10000000) function returns 1. Why?

Why parseInt(1/10000000) result 1 when the result of parseInt(1/1000000) is 0 ?

I need some analogue for Java int casting as int i = -1/10000000; which is 0 .

Should I use Math.floor for positives and Math.ceil for negatives? Or is there another solution?

+5
source share
2 answers

At first the question seems interesting. Then I looked at what 1/10000000 .

 < 1/10000000 > 1e-7 

Thus:

 < parseInt("1e-7"); // note `parseInt` takes a STRING argument > 1 

If you want to truncate an integer, you can do this:

 function truncateToInteger(real) { return real - (real % 1); } 
+10
source

parseInt expects parsing of the string argument, so it converts it to string first.

1/1000000 when converting to the string "0.000001" , parseInt then ignores everything starting with "." since it is intended only for integers, so it reads it as 0 .

1/10000000 so small that converting it to a string uses the scientific notation "1e-7" , parseInt then ignores everything starting with "e", since it is only for integers, so it reads it as 1 .

Basically, parseInt is simply not what you should be doing.

To convert a number to an integer, OR it is from 0, since any bitwise operation in JavaScript forces the number to a 32-bit int, and ORing from 0 does not change the value that goes beyond:

 >(-1/10000000)|0 0 >1234.56|0 // truncation 1234 >(2147483647+1)|0 // integer overflow -2147483648 
+6
source

Source: https://habr.com/ru/post/1209892/


All Articles