sudip_dg77 has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have this while loop:
while (my $data = $_src_dbh->get_array()) { my $record = join(",", @data). "\n"; print $record; }
When I get the output I get it as follows:
Name, Status, Amount John, Active, 100.19 Shiela, Active, 99.40 Bela, Active, 1.0

But I do not want the decimal part printed in the above output.
I mean wherever there is 100.19 it should be 100 only, where it is 99.40 it should be 99 only and where it is 1.0 it should be 1 only.

Is there an easy way to do it inside the while loop above?
Thanks for you help.

Replies are listed 'Best First'.
Re: Trimming of the decimal part.
by citromatik (Curate) on Apr 23, 2008 at 15:19 UTC

    Use printf or sprintf instead:

    perl -e '$x=100.09;printf "%d\n",$x' 100

    Update: In your case, something like this should work (note that I have corrected a reference to $data too):

    while (my $data = $_src_dbh->get_array()) { my $record = sprintf "%s%s%d",join(",", @$data); print "$record\n"; }

    Update2: Oops!, sprintf should be called without joining the array. Sorry. This is the corrected version:

    while (my $data = $_src_dbh->get_array()) { my $record = sprintf "%s,%s,%d\n",@$data); print $record; }

    citromatik

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Trimming of the decimal part.
by mscharrer (Hermit) on Apr 23, 2008 at 17:06 UTC
    You can remove the fractional part by using int( ). If you don't know in advance which array element is a number you can use looks_like_number( ) from the Scalar::Utils package:

    Untested:

    use strict; use warnings; use Scalar::Utils qw(looks_like_number); while (my $data = $_src_dbh->get_array()) { foreach my $elem (@$data) { $elem = int($elem) if looks_like_number($elem); } local $, = ','; print @$data; print "\n"; }
    I assume now that $data is an array ref and @data was a typo in your code and should have been @$data.
      It should be noted that int always rounds down, while sprintf will flexibly round the proper direction. I didn't notice which way the OP wanted, nor whether the distinction would matter in the particular case. It's a good issue of which to be aware, though.
        I know that int( ) is truncating the fractional part away, i.e. is always rounding down. The OP said: But I do not want the decimal part printed in the above output.. This means truncation to me. Maybe I took it to literal.

        So far I can remember my last encounter with true rounding in Perl the sprinf function is really the best, like you already said. For other rounding functions like floor() and ceil() the POSIX module can be used.

        Update:
        Just tested sprintf("%d") and it truncates like int(). A function which implements "normal" rounding, away from zero from .5 starting is:

        sub round ($) { return sprintf("%.0f", shift); }