···11+---
22+title: Floating-point cheat sheet for Perl
33+description: Tips for using floating-point and decimal numbers in Perl
44+---
55+66+Floating-Point Types
77+--------
88+Perl supports platform-native floating-point as scalar values; in practice this usually means [IEEE 754](/formats/fp/) double precision.
99+1010+Exact Types
1111+-------------
1212+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.
1313+1414+The Math::BigFloat extension provides an arbitrary-precision [decimal type](/formats/exact/):
1515+ use Math::BigFloat ':constant'
1616+ my $f = 0.1 + 0.2; # returns exactly 0.3
1717+The Number::Fraction extension provides a fraction type that overloads the arithmetic operators with [symbolic](/formats/exact/) fraction arithmetic:
1818+ use Number::Fraction ':constants';
1919+ my $f = '1/2' - '1/3'; # returns 1/6
2020+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.
2121+2222+How to Round
2323+------------
2424+To get a string:
2525+ $result = sprintf("%.2f", 1.2345); # returns 1.23
2626+To format output:
2727+ printf("%.2f", 1.2); # prints 1.20
2828+Note that this implicitly uses [round-to-even](/errors/rounding/). The variable <code>$#</code> contains the default format for printing numbers, but its use is considered deprecated.
2929+3030+The Math::Round extension provides various functions for rounding floating-point values:
3131+ use Math::Round qw(:all);
3232+ $result = nearest(.1, 4.567) # prints 4.6
3333+ $result = nearest(.01, 4.567) # prints 4.57
3434+The Math::BigFloat extension also supports various [rounding modes](/errors/rounding/):
3535+ use Math::BigFloat;
3636+ my $n = Math::BigFloat->new(123.455);
3737+ my $f1 = $n->round('','-2','common'); # returns 123.46
3838+ my $f2 = $n->round('','-2','zero'); # returns 123.45
3939+4040+Resources
4141+---------
4242+* [Semantics of numbers and numeric operations in Perl](http://perldoc.perl.org/perlnumber.html)
4343+* [sprintf function](http://perldoc.perl.org/functions/sprintf.html)
4444+* [Math::Round extension](http://search.cpan.org/dist/Math-Round/Round.pm)
4545+* [Number::Fraction extension](http://search.cpan.org/~davecross/Number-Fraction-1.13/lib/Number/Fraction.pm)
4646+* [Math::BigRat extension](http://search.cpan.org/~flora/Math-BigRat-0.26/lib/Math/BigRat.pm)
4747+* [Math::BigFloat](http://search.cpan.org/~flora/Math-BigInt-1.95/lib/Math/BigFloat.pm)
4848+