in reply to Rounding numbers

#!/usr/bin/perl -w use 5.016; # rounded-1079543.pl - Round to 2 decimal places using regexen # (even though printf/sprintf would be preferred) # update 2: as Laurent_R notes, this is truncation, not ro +unding. # but it is what OP asked for. my $num = 3.333333333; $num =~ /(\d*\.\d{2})/; my $roundednum = $1; say $roundednum; # or my $num2 = 5.5555555; $num2 =~ s/(\d*\.)(\d)(\d).*/$1$2$3/; my $rounded2 = $num2; say $rounded2; =head execution: C:>rounded-1079543.pl 3.33 5.55 =cut

Reformatted (belatedly): added code tags when the (well-deserved) downvotes accumulated sufficiently to attract my attention.
Is my impression that answers submitted to the Q&A editors are NOT editable by the author, until approved into public use?
If so, maybe we should make the input box for Q&A look like (and behave like) those for SOPW, etc.

Replies are listed 'Best First'.
Re^2: Rounding numbers
by Laurent_R (Canon) on Mar 27, 2014 at 07:44 UTC
    It seems to me that your regexes are truncating the numbers, not rounding them.
      Correct!

      That's what OP's examples and problem statement specify, despite misuse of "rounding."


      Questions containing the words "doesn't work" (or their moral equivalent) will usually get a downvote from me unless accompanied by:
      1. code
      2. verbatim error and/or warning messages
      3. a coherent explanation of what "doesn't work actually means.
        I did not understand that from the OP's examples and problem statement, but if you agree that you proposed solution is truncating the numbers, not rounding them, then it is fine for me and I also agree with you, and it is a possible solution to the OP's problem.