We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

perl question

rongz
rongz asked
on
Medium Priority
210 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");
    }

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




Comment
Watch Question

Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

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

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

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

Author

Commented:
i think the second comment made by ozo is perfect.

Commented:
Didn't you want ozo's answer?
If there's been a misunderstanding here, just let us know.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.