Home > OS >  Remove upfront zeros from floating point lower than 1 in Perl
Remove upfront zeros from floating point lower than 1 in Perl

Time:02-01

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.

CodePudding user response:

A number with leading zeros is interpreted as octal, e.g. 000000.1 is 01. I presume you have a string as input, e.g. 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

CodePudding user response:

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

my $str = '0000.1';

my $num = 0   $str;

An example, to run from the command-line:

perl -wE'$n = shift; $n = 0   $n; say $n'  0000.1

Prints 0.1

Another, more "proper" way is to format that string (0000.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 (0000.1, rather than '000.1') would be treated as an octal number except that the decimal point renders that moot; so it is tortured into a number giving unrelated values.

I am not sure how one could get a realistic input to look 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'.

  • Related