in reply to Decimal numbers calculations done inconsistently: Odd behavior!

Hello ferdi, and welcome to the Monastery!

To expand a little on the answers given above: if you change the print statement to this:

printf "%d %d %d %.15f %.15f %s %.0f %.0f %.0f %.0f\n", $date, $time1, $time2, $stretch, $stretcher, $identifier, $ope +n, $high, $low, $close;

you will see:

1:39 >perl 1187_SoPW.pl 20120620 93100 100000 7.000000000000000 43.000000000000000 Red 84 84 8 +4 84 20120621 93100 100000 28.999999999999091 32.000000000000909 Red 81 81 +80 80 20120622 93100 100000 27.999999999998181 39.000000000000000 Green 79 7 +9 78 79 20120625 93100 100000 4.999999999999091 76.000000000000909 Red 79 79 7 +8 78 1:40 >

which shows why the numbers in the first line are printed as integers. One way to convert a floating-point number to the closest integer is to add 0.5 and then truncate:

1:40 >perl -wE "my $fp = 28.999999999999091; my $int = int($fp + 0.5) +; say $int;" 29 1:47 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Decimal numbers calculations done inconsistently: Odd behavior!
by BillKSmith (Monsignor) on Mar 19, 2015 at 20:20 UTC
    This works well if you expect the floating point number to be near an integer. If you expect 3.5 to round to 4, it will fail if your 3.5 is really 3.49999999...
    Bill
      That may be slightly more complicated than that. IEEE Standard rounding rules are somewhat unexpected to many people. This is what true rounding is supposed to be according to IEEE:
      $ perl -e 'my $c = 0.5; $c +=1 and printf "%f -> %0.0f\n", $c, $c for +1..10;' 1.500000 -> 2 2.500000 -> 2 3.500000 -> 4 4.500000 -> 4 5.500000 -> 6 6.500000 -> 6 7.500000 -> 8 8.500000 -> 8 9.500000 -> 10 10.500000 -> 10
      Round up if the previous digit is odd and round down if it is even.

      Je suis Charlie.