Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Dividing and format with regular expression the perl way

by Roger (Parson)
on Nov 27, 2003 at 20:15 UTC ( [id://310592]=note: print w/replies, xml ) Need Help??


in reply to Dividing and format

Yes, you can certainly do this without using printf or sprintf. Number can be treated as string in perl. I will provide a simple regular expression solution since nobody has thought about it yet. ;-)

#!/usr/local/bin/perl -w use strict; my $xx = 12000/1000; # wanted result is 12.0 my $yy = 12678/1000; # wanted result is 12.7 - rounded up print "\$xx = ", rounding_with_regex($xx), "\n"; print "\$yy = ", rounding_with_regex($yy), "\n"; sub rounding_with_regex { my $num = shift; $num += 0.05; # want to round up (as number) $num =~ s/\.(\d).*/.$1/; # perform the rounding (as string) return $num; }
And the output is exactly as required -
$xx = 12.0 $yy = 12.7

Replies are listed 'Best First'.
Re: Re: Dividing and format with regular expression the perl way
by Anonymous Monk on Nov 27, 2003 at 20:35 UTC
    $num =~ s/\.(\d).*/.$1/; # perform the rounding (as string)

    Oi Vay! Why (oh why) do you have that trailing dot-star in your regex? I see this with both neophyte and experienced RE users and I have yet figure out what misconception leads to this practice. Any ideas?

      Well, just drop trailing dot-star in the regex and see the result. ;-)

      I want to get rid of anything after the first decimal point, the tailing (.*) let me do that. Of course I can also rewrite the regular expression as -
      $num =~ s/\.(\d)\d+/.$1/; # perform the rounding (as string)
      But that requires 3 characters, and I am just too lazy. Besides there is an assumption that whatever passed in is a floating point.

      In this case, it removes anything after the first decimal. Perhaps you are thinking of needless .* at the end of a m//?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://310592]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-19 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found