in reply to Re^2: Coping with decimals
in thread Coping with decimals

The standard Perl approach to rounding numbers (with sprintf) amounts to using a string manipulation for what is arguably an arithmetic task. Did you have any particular error in mind?

When I first saw the question, the two solutions I thought of were $x - int( $x ) or indeed something along the lines of $x =~ s/\d+(?=\.)//, and I'm curious about what errors could have resulted from the latter approach.

the lowliest monk

Replies are listed 'Best First'.
Re^4: Coping with decimals
by BrowserUk (Patriarch) on Jun 02, 2005 at 13:28 UTC

    A loss of precision:

    #! perl -slw use strict; my $pi = 3.141592653589793238462643383279502; print $pi - int( $pi ); ( my $fract = $pi ) =~ s/\d+(?=\.)//; print $fract; __END__ P:\test>462902 0.141592653589793 .14159265358979

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
Re^4: Coping with decimals
by mikeraz (Friar) on Jun 02, 2005 at 16:26 UTC

    Having a mental map that considers strings numbers and numbers strings allows one to make subtle errors in their programs.

    In fact, sprintf returns a string after doing an arithmatic operation. Compare a 2 deciaml point operation via sprintf:

    my $num = 4.62899; $round = sprintf "%.2f", $num; print "$round\n";

    prints 4.63, which is not a trimming of the string to two decimal places.

    For another example consider this snip and output.

    my $string = "0.0"; print "string $string is ", ($string ? "True" : "False"), "\n"; print "string $string is ", ($string+0 ? "True" : "False"), "\n";

    Which prints:
    string 0.0 is True
    string 0.0 is False

    Be Appropriate && Follow Your Curiosity

      prints 4.63, which is not a trimming of the string to two decimal places.

      That's not a bug; it's a feature :-) . Seriously, that's the documented behavior for sprintf, and precisely why it is the standard way to do rounding in Perl.

      the lowliest monk