简体   繁体   中英

Remove upfront zeros from floating point lower than 1 in Perl

I would like to normalize the variable from ie. 00000000.1, to 0.1 using Perl

my $number = 000000.1;

$number =\~ s/^0+(\.\d+)/0$1/;

Is there any other solution to normalize floats lower than 1 by removing upfront zeros than using regex?

When I try to put those kind of numbers into an example function below

test(00000000.1, 0000000.025);

sub test {
    my ($a, $b) = @_;
    print $a, "\n";
    print $b, "\n";
    print $a + $b, "\n";

}

I get

01
021
22

which is not what is expected.

A number with leading zeros is interpreted as octal, eg 000000.1 is 01 . I presume you have a string as input, eg my $number = "000000.1" . With this your regex is:

my $number = "000000.1";
$number =~ s/^0+(?=0\.\d+)//;
print $number;

Output:

0.1

Explanation of regex:

  • ^0+ -- 1+ 0 digits
  • (?=0\.\d+) -- positive lookahead for 0. followed by digits

Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

Simplest way, force it to be treated as a number and it will drop the leading zeros since they are meaningless for decimal numbers

my $str = '000.1';
...
my $num = 0 + $str;

An example, to run from the command-line:

perl -wE'$n = shift; $n = 0 + $n; say $n' 000.1

Prints 0.1

Another, more "proper" way is to format that string ( '000.1' and such) using sprintf . Then you do need to make a choice about precision, but that is often a good idea anyway

my $num = sprintf "%f", $str;    # default precision

Or, if you know how many decimal places you want to keep

my $num = sprintf "%.3f", $str; 

The example in the question is really invalid. An unquoted string of digits which starts with a zero ( 077 , rather than '077' ) would be treated as an octal number except that the decimal point (in 000.1 ) renders that moot as octals can't be fractional; so, Perl being Perl, it is tortured into a number somehow, but possibly yielding unintended values.

I am not sure how one could get an actual input like that. If 000.1 is read from a file or from the command-line or from STDIN ... it will be a string, an equivalent of assigning '000.1'

SeeScalar value constructors in perldata , and for far more detail, perlnumber .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM