Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for this Perl formatting error?

Tags:

perl

$str =sprintf "%014ld", "2555600000";
print $str;

This gives me the result:

-0001739367296

a negative number. Is there a reason for this behavior?

like image 755
sab Avatar asked Dec 01 '25 08:12

sab


2 Answers

2555600000 is too big to fit in a 32-bit signed integer. Converted to binary, it's 10011000 01010011 01011100 10000000, which stands for -0001739367296 when interpreted as a signed 32-bit integer.

Your options are:

my $str = sprintf("%014u", 2555600000);     # unsigned integer
my $str = sprintf("%014.0f", 2555600000);   # floating point
my $str = sprintf("%014s", 2555600000);     # string

The first one works for this number, but not for much higher numbers. The second one can become inaccurate for very high numbers. (But with the standard floating point "double" you should easily be accurate for the 14 digits you're using. The third one might be the easiest, just treat it as a string and forget that it's a number.

To see how many bits your version is using, you can run perl -V. Example output:

...
intsize=4, longsize=4, ptrsize=4, doublesize=8, byteorder=1234
...

so my Perl is using 4-byte, 32-bit, integers.

like image 76
mscha Avatar answered Dec 03 '25 21:12

mscha


$ perl -e '$str =sprintf "%014ld", "2555600000"; print $str, "\n";'
00002555600000

It works for me. However, the number you give is bigger than a 32 bit signed integer can hold, so maybe your result means you're on a 32 bit machine?

like image 28
Paul Tomblin Avatar answered Dec 03 '25 21:12

Paul Tomblin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!