Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl weird behaviour in number with decimal point

So I was writing a perl program to do some calculation and I had put a floating point number as

$x = 00.05;

if I print

print $x * 100.0;

It returns 500.0

But if I do

$x = 0.05; print $x * 100.0;

it prints correctly 5.0;

What is this behaviour? Is there any convention I have to obey that I am missing?

like image 722
zephyr0110 Avatar asked Dec 23 '22 17:12

zephyr0110


1 Answers

A leading zero means an octal constant, so when you do

my $x = 00.05;

you actually do string concatenation of two octal numbers:

my $x = 00 . 05; # The same as "0" . "5"

which gives you the string "05" and later you do

print $x * 100.0;  # prints 500

since perl interprets as "05" as the number 5

like image 189
Håkon Hægland Avatar answered Feb 06 '23 17:02

Håkon Hægland