如何使用 Perl 将字符串转换为浮点数?

发布于 2024-08-17 05:36:23 字数 170 浏览 4 评论 0原文

有没有像 int() 这样的函数可以将字符串转换为浮点值? 我当前正在使用以下代码:

$input=int(substr($line,1,index($line,",")-1));

我需要将 substr 返回的字符串转换为浮点数。

Is there any function like int() which can convert a string to float value?
I'm currently using the following code:

$input=int(substr($line,1,index($line,",")-1));

I need to convert the string returned by substr to float.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长梦不多时 2024-08-24 05:36:23

只需使用它即可。在 Perl 中,看起来像数字的字符串就是数字。

现在,如果您想在使用它之前确定它是一个数字,那么 Scalar::Util 中有一个实用程序方法可以做到这一点:

use Scalar::Util qw/looks_like_number/;

$input=substr($line,1,index($line,",")-1);

if (looks_like_number($input)) {
    $input += 1; # use it as a number!
}

基于示例输入您在评论中留下的,提取数字的更可靠的方法是:

$line =~ /([^\[\],]+)/; # <-- match anything not square brackets or commas
$input = $1;            # <-- extract match

Just use it. In Perl, a string that looks like a number IS a number.

Now, if you want to be sure that the thing is a number before using it then there's a utility method in Scalar::Util that does it:

use Scalar::Util qw/looks_like_number/;

$input=substr($line,1,index($line,",")-1);

if (looks_like_number($input)) {
    $input += 1; # use it as a number!
}

Based on the sample input you left in the comments, a more robust method of extracting the number is:

$line =~ /([^\[\],]+)/; # <-- match anything not square brackets or commas
$input = $1;            # <-- extract match
为人所爱 2024-08-24 05:36:23

I don't know what your data looks like, but you do realize that the third argument to substr is a length, not a position, right? Also, the first position is 0. I suspect you aren't getting the data you think you are getting, and it mostly accidently works because you are starting at the beginning of the string and are only off by one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文