如何检查一个数字是浮动或整数?
如何找到一个数字是 float
或整数
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何找到一个数字是 float
或整数
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(30)
除以1时检查其余部分:
如果您不知道该参数是一个数字,则需要两个测试:
更新2019
编写了这个答案5年后,在ECMA脚本2015中标准化了解决方案。该解决方案被涵盖在此答案中。
check for a remainder when dividing by 1:
If you don't know that the argument is a number you need two tests:
Update 2019
5 years after this answer was written, a solution was standardized in ECMA Script 2015. That solution is covered in this answer.
有一种称为
number.isinteger()
的方法,该方法当前在IE以外的所有内容中都实现。但是,对于大多数使用情况,最好使用
number.issafeinteger
,它还检查该值是否如此之高/低,以至于任何小数点位置都会丢失。 isinteger pollyfill。)There is a method called
Number.isInteger()
which is currently implemented in everything but IE. MDN also provides a polyfill for other browsers:However, for most uses cases, you are better off using
Number.isSafeInteger
which also checks if the value is so high/low that any decimal places would have been lost anyway. MDN has a polyfil for this as well. (You also need theisInteger
pollyfill above.)尝试这些函数来测试一个值是否是一个没有分数部分的数字原始值,并且在可以表示为确切整数的大小限制之内。
Try these functions to test whether a value is a number primitive value that has no fractional part and is within the size limits of what can be represented as an exact integer.
为什么不这样的事情:
Why not something like this:
您可以使用简单的正则表达式:
或者也可以根据需要使用以下功能。它们是由
is_int()
=>检查变量类型是否是整数,并且其内容是否是整数is_float() a> =>检查变量类型是否为float,其内容是否float
ctype_digit() a> =>检查变量类型是否为字符串,以及其内容是否仅具有十进制数字
更新1
现在也检查负数,谢谢@chrisbartley comment !
You can use a simple regular expression:
Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.
is_int()
=> Check if variable type is integer and if its content is integeris_float()
=> Check if variable type is float and if its content is floatctype_digit()
=> Check if variable type is string and if its content has only decimal digitsUpdate 1
Now it checks negative numbers too, thanks for @ChrisBartley comment!
2022更新 - 我们可以简单地使用该数字的方法。
检查整数还是浮动:
号码
。
number.isinteger(val)
检查是否float(不是整数):
!! number.Isfinite(val)
2022 update - We could simply use the Number's methods.
Check if integer or float :
Number.isFinite(val)
Check if integer :
Number.isInteger(val)
Check if float (not integer) :
!Number.isInteger(val) && Number.isFinite(val)
以下是有效的功能,可以检查值是数字还是可以安全转换为 a的数字:
对于整数(如果值为float,则将返回false):
此处的效率是ParseInt(当值已经是一个数字时,可以避免使用parsenumber)。两种解析函数始终首先转换为字符串,然后尝试解析该字符串,如果该值已经是数字,那将是浪费。
感谢这里的其他帖子提供了进一步的优化想法!
Here are efficient functions that check if the value is a number or can be safely converted to a number:
And for integers (would return false if the value is a float):
The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.
Thank you to the other posts here for providing further ideas for optimization!
适用于所有情况。
works for all cases.
这个呢?
How about this one?
我们可以通过
isinteger
函数进行检查。IE号将返回true,float返回false
We can check by
isInteger
function.ie number will return true and float return false
正如其他人提到的那样,您只有JS的双打。那么,如何定义一个数字是整数?只需检查圆形数字是否等于自身:
As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:
这是我在整数中使用的内容:
简短,不错:)一直在工作。这就是戴维·弗拉纳根(David Flanagan)暗示的话,如果我没记错的话。
Here's what I use for integers:
Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.
简单的整数测试:
很有意义:如果JavaScript可以将某些内容转换为整数,并且通过转换,它变得完全相同,那么您的操作数就是整数。
控制台的测试用例:
这使很多人感到困惑。每当有0.0的东西时,它不再是浮子。这是一个整数。或者,您可以将其称为“数字事物”,因为当时没有严格的区别。
因此,基本上,您所能做的就是检查整数是否接受1.000是整数的事实。
有趣的旁注
有关于大量数字的评论。巨大的数字意味着这种方法没有问题;每当Parseint无法处理数字(因为它太大)时,它将返回实际值以外的其他内容,因此测试将返回false。看:
我于2014年在IE8上进行了测试,然后在Chrome上2021,两个都返回“ A is还可以; B失败”,这意味着如果一个数字太大,它就不再是整数了。
20数字应该足以让任何人引用经典。
Simple integer test:
Makes sense: if JavaScript can convert something to an integer, and by the conversion it becomes the exact same thing, then your operand was an integer.
Test cases for console:
This confuses a lot of people. Whenever something is .0, it's not a float anymore. It's an integer. Or you can just call it "a numeric thing" for there is no strict distinction like back then in C. Good old times.
So basically, all you can do is check for integer accepting the fact that 1.000 is an integer.
Interesting side note
There was a comment about huge numbers. Huge numbers mean NO problem for this approach; whenever parseInt is unable to handle the number (for it's too big) it will return something else than the actual value so the test will return FALSE. Look:
I tested this in 2014 on IE8, then 2021 on Chrome, both returns "a is ok; b fails" which means if a number is too big, it can't be an integer anymore.
20 digits ought to be enough for anybody, to quote a classic.
任何具有零小数零件(例如1.0、12.00、0.0)的浮点数均隐含地施放给整数,因此无法检查它们是否浮动。
Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.
没有这样做的情况。
Haven't had a case where this didn't do the job.
在这里尝试一些答案,我最终写了这个解决方案。
这也与字符串中的数字一起起作用。
Trying some of the answers here I ended up writing this solution.
This works also with numbers inside a string.
这确实取决于您要实现的目标。如果您想“模仿”强烈键入的语言,那么我建议您不要尝试。正如其他人提到的,所有数字具有相同的表示形式(相同类型)。
使用 claudiu 提供的内容:
isInteger(1.0)
- > 在常识上看起来不错,但是在C之类的东西中,您会得到
false
It really depends on what you want to achieve. If you want to "emulate" strongly typed languages then I suggest you not trying. As others mentioned all numbers have the same representation (the same type).
Using something like Claudiu provided:
isInteger( 1.0 )
-> truewhich looks fine for common sense, but in something like C you would get
false
它确实不必那么复杂。整数的parsefloat()和parseint()等效的数值将相同。因此,您可以这样做:
那么,
这也将允许进行字符串检查,因此并不严格。如果需要强的类型解决方案(又名,无法与字符串一起使用):
It really doesn't have to be so complicated. The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:
Then
This will also allow for string checks and thus is not strict. If want a strong type solution (aka, wont work with strings):
这是检查int和float
或float或
THIS IS FINAL CODE FOR CHECK BOTH INT AND FLOAT
OR
该解决方案对我有用。
This solution worked for me.
请尝试此尝试
当返回值为false时,
,表示输入值为浮点数或浮点字符串,否则输入值是整数NUMBEF或整数字符串。基本上,它需要检查精度值不等于零。
另一个也是检查正确的字符串号。
try this
when the return value is false means the input value is float number or float string, otherwise the input value is integer numbef or integer string.
basically it needs to check the precision value for not equal to zero.
another one is to check the correct string number also.
比较代码> 结果与
ceil()
结果。Compare that
floor()
result is not the same asceil()
result.对于整数,我使用这个
For integers I use this
在Java脚本中,所有数字均为
内部64位浮点
,与Java中的Double相同。JavaScript中没有不同类型,所有类型均由类型
number
表示。因此,您将无法制作实例
检查。但是,您可以使用上述解决方案来找出它是否是分数数。 Java脚本的设计师以一种类型的方式感觉到他们可以避免多种类型的铸造错误。In java script all the numbers are
internally 64 bit floating point
, same as double in java.There are no diffrent types in javascript, all are represented by type
number
. Hence you wil l not be able make ainstanceof
check. However u can use the above solutions given to find out if it is a fractional number. designers of java script felt with a single type they can avoid numerous type cast errors.对于那些好奇的人,我使用基准测试了这篇文章中最上投票的答案(以及今天发布的答案),这是我的结果:
For those curious, using Benchmark.js I tested the most up-voted answers (and the one posted today) on this post, here are my results:
我喜欢这个小功能,它将返回正整数和负面整数:
这是因为1或“ 1”变为“ 1.0”,isnan()返回false(然后我们否定并返回),但1.0或“”或“” 1.0“变为“ 1.0.0”,而“字符串”变为“ string.0”,它们都不是数字,因此isnan()返回false(并且再次被否定)。
如果您只需要积极的整数,则有一个变体:
或者,对于负整数:
ispostivelInt()通过移动串联的数字字符串在要测试的值之前来起作用。例如,IspostiveInt(1)在评估“ 01”的ISNAN()中结果,该评估false。同时,IspostiveInt(-1)在评估“ 0-1”的ISNAN(-1)中,该评估是正确的。我们否定了回报价值,这给了我们想要的东西。 isneNgativeInt()的工作原理类似,但没有否定isnan()的返回值。
编辑:
我的原始实现也将在数组和空字符串上返回真实。此实现DOE没有那种缺陷。如果Val不是字符串或数字,或者是空字符串,则它还具有提早返回的好处,在这些情况下它使其更快。 可以通过更换前两个子句来进一步修改它
如果您只想匹配字面数字(而不是字符串)
编辑:
我无法发布评论,则 :我将其添加到答案中。 @asok发布的基准非常有用。但是,最快的功能不符合要求,因为它对于浮子,阵列,布尔值和空字符串也返回。
我创建了以下测试套件来测试每个函数,还将答案添加到列表中(功能8,解析字符串和功能9,但没有):
我还用功能#8添加到基准测试中列表。我不会发布结果,因为它们有点尴尬(例如,功能不是很快)...
(删节 - 我删除了成功的测试,因为输出很长)如下:
我剩下的失败中,您可以看到每个函数的失败位置,并且(字符串)'#'测试,因此您可以看到每个函数如何处理字符串中的整数和浮点值,因为有些人可能希望将它们解析为数字,而有些则可能不会。 。
在测试的10个功能中,实际上适合OP的要求的功能是[1,3,5,6,8,9]
I like this little function, which will return true for both positive and negative integers:
This works because 1 or "1" becomes "1.0", which isNaN() returns false on (which we then negate and return), but 1.0 or "1.0" becomes "1.0.0", while "string" becomes "string.0", neither of which are numbers, so isNaN() returns false (and, again, gets negated).
If you only want positive integers, there's this variant:
or, for negative integers:
isPositiveInt() works by moving the concatenated numeric string ahead of the value to be tested. For example, isPositiveInt(1) results in isNaN() evaluating "01", which evaluates false. Meanwhile, isPositiveInt(-1) results in isNaN() evaluating "0-1", which evaluates true. We negate the return value and that gives us what we want. isNegativeInt() works similarly, but without negating the return value of isNaN().
Edit:
My original implementation would also return true on arrays and empty strings. This implementation doe not have that defect. It also has the benefit of returning early if val is not a string or number, or if it's an empty string, making it faster in these cases. You can further modify it by replacing the first two clauses with
if you only want to match literal numbers (and not strings)
Edit:
I can't post comments yet, so I'm adding this to my answer. The benchmark posted by @Asok is very informative; however, the fastest function does not fit the requirements, as it also returns TRUE for floats, arrays, booleans, and empty strings.
I created the following test suite to test each of the functions, adding my answer to the list, as well (function 8, which parses strings, and function 9, which does not):
I also reran the benchmark with function #8 added to the list. I won't post the result, as they're a bit embarrassing (e.g. that function is NOT fast)...
The (abridged -- I removed successful tests, since the output is quite long) results are as follows:
I've left in failures so you can see where each function is failing, and the (string) '#' tests so you can see how each function handles integer and float values in strings, as some may want these parsed as numbers and some may not.
Out of the 10 functions tested, the ones that actually fit OP's requirements are [1,3,5,6,8,9]