Solved

perl question

Posted on 1998-06-20
5
167 Views
Last Modified: 2010-03-04
I wrote following code. But the problem is suppose $1=10, $2=3.the $value will be 3.33333. But how can I only keep 2
characters after decimal point.That is, I want the value of $value pushed into @array is 3.33.

    ----------------------------------------
    $formula='$1/$2';

    while(<>){
    /^(/S+)/s+(/S+)/
      if($2 == 0){
         $value=0; #is there any concise way to do this?
      }else{
         $value=eval($formula);}
      push(@array,$1,$2,$value,"\n");
    }

    ............




0
Comment
Question by:rongz
  • 2
  • 2
5 Comments
 
LVL 4

Accepted Solution

by:
martinag earned 100 total points
ID: 1207935
Multiply with 100, round and divide by 100.

$value *= 100;
$value = int($value);
$value /= 100;

For example, 3.3333 is multiplied with 100.
That gives us 333.33
Then we round it: 333
When we divide it by 100 we get 3.33
0
 
LVL 84

Expert Comment

by:ozo
ID: 1207936
push(@array,$1,$2,$2&&sprintf("%.2f",eval($formula))) if /^(\S+)\s+(\S+)/;

0
 
LVL 84

Expert Comment

by:ozo
ID: 1207937
# or just in case $2 == 0 but not $2 eq '0':
  push @array,$1,$2,0+$2&&sprintf "%.2f",eval $formula
0
 

Author Comment

by:rongz
ID: 1207938
i think the second comment made by ozo is perfect.
0
 
LVL 4

Expert Comment

by:martinag
ID: 1207939
Didn't you want ozo's answer?
If there's been a misunderstanding here, just let us know.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question