title | description |
---|---|
Floating-point cheat sheet for Perl |
Tips for using floating-point and decimal numbers in Perl |
Perl supports platform-native floating-point as scalar values; in practice this usually means IEEE 754 double precision.
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.
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
- Semantics of numbers and numeric operations in Perl
- sprintf function
- Math::Round extension
- Number::Fraction extension
- Math::BigRat extension
- Math::BigFloat extension
Perl 支持作为标量的平台原生浮点;实际上就是指 IEEE 754 双精度。
Perl 可以用字符串的方式存储小数,但内置的算数运算会把它们转换成整数或者浮点数来进行运算。
Math::BigFloat
扩展提供了 arbitrary-precision 小数类型:
use Math::BigFloat ':constant'
my $f = 0.1 + 0.2; # 返回 exactly 0.3
Number::Fraction
扩展提供了分数类型,它用分数算数里的符号重载了算数运算符:
use Number::Fraction ':constants';
my $f = '1/2' - '1/3'; # 返回 1/6
Math::BigRat
扩展提供了类似的功能。它的优点在于兼容 Math::BigInt
和 Math::BigFloat
扩展,但它好像不支持分数字面量。
得到字符串:
$result = sprintf("%.2f", 1.2345); # 返回 1.23
如何格式化输出:
printf("%.2f", 1.2); # 打印 1.20
注意,这个实现使用 round-to-even。 变量 $#
存有打印数字的缺省格式,但这不推荐使用。
Math::Round
扩展提供不同的不同的函数来取整浮点值:
use Math::Round qw(:all);
$result = nearest(.1, 4.567) # 打印 4.6
$result = nearest(.01, 4.567) # 打印 4.57
Math::BigFloat
扩展也支持不同的取整模式:
use Math::BigFloat;
my $n = Math::BigFloat->new(123.455);
my $f1 = $n->round('','-2','common'); # 返回 123.46
my $f2 = $n->round('','-2','zero'); # 返回 123.45