in reply to Arithmetic with fractions

$fraction = '32 2/5'; &fconv(\$fraction); sub fconv { my $f = shift; if ($$f =~ /((\d+) )?(\d+) ?\/ ?(\d+)/) { $$f = $2 + $3/$4; } }
This will convert a fraction or mixed number of any form to a decimal equivalent. The following are some possibilities:

2/5
2 / 5
2 /5
32 2/5
32 2 / 5

Replies are listed 'Best First'.
Re^2: Arithmetic with fractions
by tachyon (Chancellor) on Sep 22, 2004 at 07:33 UTC

    Why are you capturing to $1? You don't deal with signs, so how about:

    sub fconv { my $f = shift; if ($$f =~ m!([\-\+]*)\s*(?:(\d+)\s+)?(\d+)\s*/\s*(\d+)!) { $$f = $2 + $3/$4; $$f = -$$f if $1 eq '-'; } }

    cheers

    tachyon

      $fraction = '-32 2/5'; &fconv(\$fraction); sub fconv { my $f = shift; if ($$f =~ /(-?) ?((\d+) )?(\d+) ?\/ ?(\d+)/) { $$f = ($1 eq '-' ? -1 : 1) * ($3 + $4/$5); } }
      There, it now works with negatives. My bad on the earlier version :)

      As for Perl's problems with number management, that can't really be helped. You can always use the fractions class mentioned above, or round your results to the nearest thousandth, which should produce the same results.