How to convert a string to a number (float) in Perl

edit 2020: Answer is wrong, see comment below. I am not permitted to delete an accepted answer.


I am answering the literal question. Perhaps you want to format the number for display.

Both expressions

sprintf '%.2f', '10.0500000'
sprintf '%.2f', 10.0500000

return the string 10.05.


In Perl, scalars are not typed. Instead, operators are. So when you do $a . "1" you use $a as a string, and when you do $a + 1 you use $a as a number. Perl will do its best to figure out what a scalar means for a given operation. So for most cases, "converting" is done implicitly for you.

If you need to verify that your string can indeed be converted, use regular expressions.

Here is one discourse on how to do that: http://www.regular-expressions.info/floatingpoint.html


Well, you could add 0 as well :-)

You should not care too much about the internal representation of a scalar in Perl, unless you're doing some weird things (and please tell us if you are). Whatever looks like a number is a number.

Or do you need to check if the string is a "real" number? Well, actually, any string is. There's a nice article Is it a Number on this topic. That link is to the Wayback Machine because the original has been deleted from perl.com.

Tags:

Perl