检查数字是 int 还是 float [英] check if a number is int or float

查看:76
本文介绍了检查数字是 int 还是 float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 perl 中,我想检查给定的变量是否包含 not 的浮点数.要检查这个我正在使用,

In perl, I want to check if the given variable holds a floating point number of not. To check this I am using,

my $Var = 0.02 # Floating point number

if (int($Var) != $Var) {

   # floating point number
}

但是上面的代码对0.0不起作用,

But the above code will not work for 0.0,

我怎样才能做到这一点?

How can I achieve this?

推荐答案

这是一个常见问题.参见 如何确定标量是否为数字/整数/整数/浮点数?

This is a FAQ. See How do I determine whether a scalar is a number/whole/integer/float?

您也可以使用 Scalar::Util::Numeric.

有趣的是,虽然

#!/usr/bin/perl

use strict; use warnings;
use Scalar::Util::Numeric qw(isint);

my $x = 0.0;
print "int\n" if isint $x;

prints int(看源码就不奇怪了),根据@tchrist的注释,看变量结构中提供的信息应该可以区分0 来自 0.0:

prints int (not surprising if you look at the source code), based on @tchrist's comment, it should be possible to look at the information supplied in the variables structure to distinguish 0 from 0.0:

#!/usr/bin/perl

use strict; use warnings;
use Devel::Peek;

my $x  = 0.0; print Dump $x;
my $y  = 0;   print Dump $y;
   $y *= 1.1; print Dump $y;

输出:

SV = NV(0x18683cc) at 0x182c0fc
  REFCNT = 1
  FLAGS = (PADMY,NOK,pNOK)
  NV = 0
SV = IV(0x182c198) at 0x182c19c
  REFCNT = 1
  FLAGS = (PADMY,IOK,pIOK)
  IV = 0
SV = PVNV(0x397ac) at 0x182c19c
  REFCNT = 1
  FLAGS = (PADMY,NOK,pNOK)
  IV = 0
  NV = 0
  PV = 0

在我看来,检查只需要查看是否设置了 NOK 标志.即使是最简单的 XS 也需要我花很长时间来编写,所以我不会提供实现.

It seems to me that the check would have to just look at if the NOK flag is set. It takes me ages to write even the simplest XS so I won't provide an implementation.

这篇关于检查数字是 int 还是 float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆