最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Function parseInt (110000000) returns 1. Why? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Dec 25, 2014 at 20:23 trejder 17.5k27 gold badges131 silver badges225 bronze badges asked Dec 25, 2014 at 20:16 timaschewtimaschew 16.6k6 gold badges64 silver badges79 bronze badges 4
  • How about the raddix parameter? It produces the same result? – Tim Vermaelen Commented Dec 25, 2014 at 20:20
  • 1 because 1/10000000 returns 1e-7 while 1/1000000 returns 0.000001. it differs how parseInt actually works... – FrEaKmAn Commented Dec 25, 2014 at 20:20
  • 1 @TimVermaelen same result. – Aleksandar Toplek Commented Dec 25, 2014 at 20:20
  • That's because the result is a float not an int. parseFloat(1/10000000) ~ 1e-7 – Edward J Beckett Commented Dec 26, 2014 at 0:10
Add a ment  | 

2 Answers 2

Reset to default 10

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
发布评论

评论列表(0)

  1. 暂无评论