Floating-point cheat sheet for Perl
Floating-Point Types
Perl supports platform-native floating-point as scalar values; in practice this usually means IEEE 754 double precision.
Exact Types
Perl can also store decimal numbers as strings, but the builtin arithmetic operators will convert them to integer or floating-point values to perform the operation.
The Math::BigFloat
extension provides an arbitrary-precision decimal type:
use Math::BigFloat ':constant'
my $f = 0.1 + 0.2; # returns exactly 0.3
The Number::Fraction
extension provides a fraction type that overloads the arithmetic operators with symbolic fraction arithmetic:
use Number::Fraction ':constants';
my $f = '1/2' - '1/3'; # returns 1/6
The Math::BigRat
extension provides similar functionality. Its advantage is compatibility with the
Math::BigInt
and Math::BigFloat
extensions, but it does not seem to support fraction literals.
How to Round
To get a string:
$result = sprintf("%.2f", 1.2345); # returns 1.23
To format output:
printf("%.2f", 1.2); # prints 1.20
Note that this implicitly uses round-to-even. The variable $#
contains the default format for printing numbers, but its use is considered deprecated.
The Math::Round
extension provides various functions for rounding floating-point values:
use Math::Round qw(:all);
$result = nearest(.1, 4.567) # prints 4.6
$result = nearest(.01, 4.567) # prints 4.57
The Math::BigFloat
extension also supports various rounding modes:
use Math::BigFloat;
my $n = Math::BigFloat->new(123.455);
my $f1 = $n->round('','-2','common'); # returns 123.46
my $f2 = $n->round('','-2','zero'); # returns 123.45
Resources
- Semantics of numbers and numeric operations in Perl
- sprintf function
- Math::Round extension
- Number::Fraction extension
- Math::BigRat extension
- Math::BigFloat extension
© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)