Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple digit length

Status
Not open for further replies.

twantrd

Technical User
Feb 13, 2005
26
0
0
US
Hey all,

I've been reading how to restrict digits to a certain length and I don't see the error.

Code:
#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

my $rounded=58.333333;
#$rounded =~ /^\d\d\.\d\d$/; # one solution
$rounded =~ /^\d{2}\.\d{2}/; # another solution
print "Rounded: $rounded\n";

I just want to print only ##.##. Thanks.
 
Sorry, pasted the wrong one. This is the correct one:

Code:
#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

my $rounded=58.333333;
#$rounded =~ /\d{1,2}\.\d{2}/;
#$rounded =~ /^\d\d\.\d\d$/;
my $value = $rounded =~ /^\d\d\.\d\d$/;
print "The rounded percentage is: $value" . "%\n";


The rounded percentage is: 1%

Thanks all....
 
When you run a regexp in scalar context, it returns the number of matches (hence, your 1). When you call it in list context, it returns the values matched.

Code:
my ($value) = $rounded =~ /(\d\d\.\d\d)/i;

Work with that.

-------------
Cuvou.com | My personal homepage
Project Fearless | My web blog
 
or:

Code:
my $rounded=58.333333;
$rounded =~ s/^(\d\d\.\d\d).*/$1/;
print $rounded

my $rounded=58.333333;
$rounded = sprintf ("%.2f",$rounded);
print $rounded

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
doh! Thanks for the answer guys!

-twantrd
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top