garrett
garrett

Reputation: 207

To what precision does perl print floating-point numbers?

my $num = log(1_000_000) / log(10);
print "num: $num\n";
print "int(num): " . int($num) . "\n";
print "sprintf(num): " . sprintf("%0.16f", $num) . "\n";

produces:

num: 6
int(num): 5
sprintf(num): 5.9999999999999991

To what precision does perl print floating-point numbers?

Using: v5.8.8 built for x86_64-linux-thread-multi

Upvotes: 5

Views: 1184

Answers (1)

ysth
ysth

Reputation: 98388

When stringifying floating point numbers, whether to print or otherwise, Perl generally uses the value of DBL_DIG or LDBL_DIG from the float.h or limits.h file where it was compiled.

This is typically the precision of the floating point type perl will use rounded down. For instance, if using a typical double type, the precision is 53 bits = 15.95 digits, and Perl will usually stringify with 15 digits of precision.

Upvotes: 10

Related Questions