javascript, parseInt behavior when passing in a float number

泄露秘密 提交于 2019-12-01 05:14:52
Barmar

I believe you are correct.

parseInt(0.00001) == parseInt(String(0.00001)) == parseInt('0.00001') ==> 0

parseInt(0.00000001) == parseInt(String(0.00000001)) == parseInt('1e-8') ==> 1

You are correct.

parseInt is intended to get a number from a string. So, if you pass it a number, it first converts it into a string, and then back into a number. After string conversion, parseInt starts at the first number in the string and gives up at the first non-number related character. So "1.e-8" becomes "1"

If you know you are starting with a string, and are just trying to get an Integer value, you can do something like.

Math.round(Number('0.00000001')); // 0

If you know you have a floating point number and not a string...

Math.round(0.00000001); // 0

You can also truncate, ceil(), or floor the number

parseInt takes each character in the first argument (converted to a string) that it recognizes as a number, and as soon as it finds a non-numeric value it ignores that value and the rest of the string. (see MDN second paragraph under "Description")

Therefore it's likely that parseInt(0.00000001) === parseInt(String(0.00000001)) === parseInt("1e-8"), which would only extract the 1 from the string yielding parseInt("1") === 1

However, there's another possibility:

From Mozilla developer network: parseInt(string, radix);

for the string argument (emphasis added): "The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored."

I think this possibility is less likely, since String(0.00000001) does not yield NAN.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!