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
The data type float has 24 bits of precision. This is equivalent to only about 7 decimal places. (The rest of the 32 bits are used for the sign and size of the number.) The number of places of precision for float is the same no matter what the size of the number.
A single-precision, floating-point number is a 32-bit approximation of a real number. The number can be zero or can range from -3.40282347E+38 to -1.17549435E-38, or from 1.17549435E-38 to 3.40282347E+38.
The number 3.0 is the literal representation of a double value (it's equivalent to 3.0d ), whereas 3.0f is a float value. The different precisions explain why you're getting different results - a double is stored using 64-bits, a float uses 32-bits.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With