To get the first 15 digits of the sum of $a
and $b
, do this:
use bigint;
my $a = "99999999999912345"; # works with or without quotes
my $b = "111"; # works with or without quotes
print substr(0 + $a + $b, 0, 15), "\n";
The reason why your code didn't work as expected is that Perl does a floating point addition for $a + $b
if both $a
and $b
are strings, even if use bigint
is in effect. Example:
use bigint;
print 1234567890123456789 + 2 , "\n"; #: 1234567890123456791
print "1234567890123456789" + 2 , "\n"; #: 1234567890123456791
print 1234567890123456789 + "2", "\n"; #: 1234567890123456791
print "1234567890123456789" + "2", "\n"; #: 1.23456789012346e+18
print 0 + 1234567890123456789 + "2", "\n"; #: 1234567890123456791
This behavior is a quirk in the Perl bigint
module. You can work it around by prepending a 0 +
(as shown above), thus forcing bigint addition instead of floating point addition. Another workaround can be Math::BigInt->new($a) + $b
instead of 0 + $a + $b
.