Why is Perl inconsistent with sprintf rounding?

前端 未结 2 1995
执笔经年
执笔经年 2021-02-20 02:20

Here is a Perl script:

#!/usr/bin/perl

use strict;
use warnings;
use feature \'say\';

my @numbers = qw(
    0.254
    0.255
    0.256
);

foreach my $number (@         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-20 03:11

    If you add this line:

    $number = sprintf '%.15f', $number;
    

    before printing, you will have:

    0.254000000000000 => 0.25
    0.255000000000000 => 0.26
    0.256000000000000 => 0.26
    100.254000000000005 => 100.25
    100.254999999999995 => 100.25
    100.256000000000000 => 100.26
    

    as you can see, 100.255 is not exactly 100.255 this is due to representation of float numbers.

提交回复
热议问题