如何使用 Perl 将字符串转换为浮点数?
有没有像 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用它即可。在 Perl 中,看起来像数字的字符串就是数字。
现在,如果您想在使用它之前确定它是一个数字,那么
Scalar::Util
中有一个实用程序方法可以做到这一点:基于示例输入您在评论中留下的,提取数字的更可靠的方法是:
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:Based on the sample input you left in the comments, a more robust method of extracting the number is:
我不知道你的数据是什么样的,但你确实意识到 substr< 的第三个参数/a> 是长度,而不是位置,对吗?另外,第一个位置是 0。我怀疑你没有得到你认为你得到的数据,而且它大多是意外地工作,因为你从字符串的开头开始,并且只偏离了一个。
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.