7

How do I convert a string to number in Perl?

Example:

$str = '10.0500000';
$number = $str * 1;  # 10.05

Is there another standard way to get 10.05 from '10.0500000' instead of multiplying with one?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bala
  • 4,427
  • 6
  • 26
  • 29

4 Answers4

11

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.

daxim
  • 39,270
  • 4
  • 65
  • 132
  • 2
    I don’t see how this answers the question. The question asks how to convert string to float, not the other way around. –  Dec 09 '20 at 20:45
  • You are correct, I screwed up. Will delete later. – daxim Dec 10 '20 at 08:20
9

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

  • 4
    Detecting a number with regex is a Perl FAQ: [How do I determine whether a scalar is a number/whole/integer/float?](http://learn.perl.org/faq/perlfaq4.html#How-do-I-determine-whether-a-scalar-is-a-number-whole-integer-float-) – daxim May 14 '12 at 14:06
  • @daxim: Ah, thank you. I knew there had to be a better source :) –  May 15 '12 at 12:15
6

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.

Borodin
  • 126,100
  • 9
  • 70
  • 144
Artyom V. Kireev
  • 588
  • 4
  • 12
4

0+ is a bit more idiomatic. It's usually used to distinguish the components of dualvars.

$ perl -E'
   system({ "nonexistant" } "nonexistant");
   say 0+$!, ": ", $!;
'
2: No such file or directory

It looks weird because it's not something you normally have to do. A number is a number, whether it's stored internally as a PV, IV, UV or NV. Forcing it to be stored as a NV (float) shouldn't be necessary, and it usually indicative of buggy design elsewhere.

ikegami
  • 367,544
  • 15
  • 269
  • 518