99

I have a string which holds a decimal value in it and I need to convert that string into a floating point variable. So an example of the string I have is "5.45" and I want a floating point equivalent so I can add .1 to it. I have searched around the internet, but I only see how to convert a string to an integer.

1
  • The question needs further detail. Is the string only composed of numerals? Alphanumeric? Ok if alphas are stripped? Is there a specific purpose for the resulting number?
    – JGurtz
    Mar 1, 2016 at 22:51

9 Answers 9

97

You don't need to convert it at all:

% perl -e 'print "5.45" + 0.1;'
5.55
3
  • 15
    @OrangeDog the OP edited the question (some months after this answer was posted) - the original question actually had floating point numbers in it.
    – Alnitak
    Mar 14, 2012 at 10:46
  • 1
    what about comparisons when the string has a comma in it?
    – Ramy
    May 22, 2014 at 15:21
  • [rabdelaz@Linux_Desktop:~/workspace/akatest_5]$perl -e 'print "nope\n" unless "1,000" > 10;' nope [rabdelaz@Linux_Desktop:~/workspace/akatest_5]$perl -e 'print "nope\n" if "1,000" > 10;'
    – Ramy
    May 22, 2014 at 15:24
79

This is a simple solution:

Example 1

my $var1 = "123abc";
print $var1 + 0;

Result

123

Example 2

my $var2 = "abc123";
print $var2 + 0;

Result

0
4
  • 9
    AFAIU this is the only answer to what was asked
    – Cougar
    May 10, 2013 at 14:17
  • 4
    Beware when adding zero to a string. If the string starts with "inf" or with "nan", the value will not be zero. E.g. my $var2 = "info123"; print $var2 + 0: Result will be: Inf Oct 14, 2016 at 15:13
  • I was doing a foreach my $i ('00'..'15') and needed to remove the leading zeros in some places. This 0+ casting to a number also achieves that.
    – stevesliva
    Nov 4, 2016 at 16:18
  • Apparently this doesn't work with hex strings: '0x14C' + 0 results in 0 (arrggg)
    – KevinHJ
    Nov 8, 2020 at 11:59
44

Perl is a context-based language. It doesn't do its work according to the data you give it. Instead, it figures out how to treat the data based on the operators you use and the context in which you use them. If you do numbers sorts of things, you get numbers:

# numeric addition with strings:
my $sum = '5.45' + '0.01'; # 5.46

If you do strings sorts of things, you get strings:

# string replication with numbers:
my $string = ( 45/2 ) x 4; # "22.522.522.522.5"

Perl mostly figures out what to do and it's mostly right. Another way of saying the same thing is that Perl cares more about the verbs than it does the nouns.

Are you trying to do something and it isn't working?

3
  • 1
    Forgive my lack of knowledge here but I don't quite get your second example. You're dividing two numbers, then multiplying them, how/why does this result in a string?
    – gideon
    Nov 28, 2012 at 14:35
  • 4
    I'm not multiplying numbers. The x is the string replication operator. Jan 7, 2013 at 9:12
  • 3
    Shouldn't it be my $string = ( 45/2 ) x 3; # "22.522.522.5" with 45 instead of 44? Otherwise I don't get where the '.5's come from in the result...
    – Vickster
    Feb 27, 2013 at 13:42
10

Google lead me here while searching on the same question phill asked (sorting floats) so I figured it would be worth posting the answer despite the thread being kind of old. I'm new to perl and am still getting my head wrapped around it but brian d foy's statement "Perl cares more about the verbs than it does the nouns." above really hits the nail on the head. You don't need to convert the strings to floats before applying the sort. You need to tell the sort to sort the values as numbers and not strings. i.e.

my @foo = ('1.2', '3.4', '2.1', '4.6');
my @foo_sort = sort {$a <=> $b} @foo;

See http://perldoc.perl.org/functions/sort.html for more details on sort

9

As I understand it int() is not intended as a 'cast' function for designating data type it's simply being (ab)used here to define the context as an arithmetic one. I've (ab)used (0+$val) in the past to ensure that $val is treated as a number.

1
  • yes, int() is being "(ab)used"; got it. Mar 24, 2020 at 1:49
7
$var += 0

probably what you want. Be warned however, if $var is string could not be converted to numeric, you'll get the error, and $var will be reset to 0:

my $var = 'abc123';
print "var = $var\n";
$var += 0;
print "var = $var\n";

logs

var = abc123
Argument "abc123" isn't numeric in addition (+) at test.pl line 7.
var = 0
5

Perl really only has three types: scalars, arrays, and hashes. And even that distinction is arguable. ;) The way each variable is treated depends on what you do with it:

% perl -e "print 5.4 . 3.4;"
5.43.4


% perl -e "print '5.4' + '3.4';"
8.8
1
  • 6
    Perl has many more types than, but for single values, it's just a single value. Nov 14, 2008 at 3:02
1

In comparisons it makes a difference if a scalar is a number of a string. And it is not always decidable. I can report a case where perl retrieved a float in "scientific" notation and used that same a few lines below in a comparison:

use strict;
....
next unless $line =~ /and your result is:\s*(.*)/;
my $val = $1;
if ($val < 0.001) {
   print "this is small\n";
}

And here $val was not interpreted as numeric for e.g. "2e-77" retrieved from $line. Adding 0 (or 0.0 for good ole C programmers) helped.

1

Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use. $a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777.

There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;.
Dump:'foo' => '42'

If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;.
Dump:'foo' => 42

After $2+0 Perl notices that you've treated $2 as a number, because you used a numeric operator.

I noticed this whilst trying to compare two hashes with Data::Dumper.

Not the answer you're looking for? Browse other questions tagged or ask your own question.