in reply to Want to Truncate A Number... NOT round it

The int() routine will truncate to an integer value, "toward zero." So int( $x * 100 ) / 100 will truncate to the penny.
my $n = 34.57889; my $na = int($n * 1000) / 1000; print "$n $na\n"; __OUTPUT__ 34.57889 34.578

A slower but interesting alternative approach... if you're dealing with long strings of digits, is to render the number to MORE digits than required, then strip the undesired digits.

my $n = 34.57889; my $na = sprintf("%3.4f", $n); $na =~ s/(?<=\.\d\d\d)\d*$//; print "$n $na\n"; __OUTPUT__ 34.57889 34.578

Take care when you're talking about "truncate", "floor", "ceiling" and "rounding" when you deal with negative numbers... make sure you're defining your problem correctly, too.

--
[ e d @ h a l l e y . c c ]

Replies are listed 'Best First'.
Re: Re: Want to Truncate A Number... NOT round it
by liz (Monsignor) on Feb 11, 2004 at 20:39 UTC
    Wouldn't
    $na =~ s/(?<=\.\d\d\d)\d*$//;
    be done better and clearer as:
    chop $na;
    ?

    Liz

    Update:
    Since the 4 digits are guaranteed by the sprintf, there should be no problem in using chop().

      Only if you're guaranteed to have exactly one digit after the desired three.

      Update in response to someone else's update: Aliens must have inserted that sprintf when I wasn't looking.