in reply to How do you ++ a fraction?
in thread Round a fraction

sub incdec { $number = shift; # do something if not /^\d*\.\d+$/ return $number+1 if $number =~ /^\d+$/; $number =~ /\.(\d+)$/; return $number + ("1E-".length($1); } for $n (1, .004, 1.99, 1.79, 1.009999) { print "$n++ = ".incdec($n)."\n"; }

gives:

1++ = 2 0.004++ = 0.005 1.99++ = 2 1.79++ = 1.8 1.009999++ = 1.01

Update: use E notation

--
Steve Marvell

Replies are listed 'Best First'.
Re: Re: How do you ++ a fraction?
by fglock (Vicar) on Aug 02, 2002 at 14:24 UTC

    Thanks.

      (0.1 ** length($1)) could also be written:
     ("1E-" . length($1))

    update: This is what I came up with:

    $frac = shift; $frac =~ s/(\d+).$/$1/; # remove last digit & get fraction size $frac += "1E-" . length($1); # add 1E-(size) => 0.0001 print $frac;

    Works for "0.123999", "10.12399" and ".12399"

    The result is weird when the number does not have a fractional part, but that is not my case.

Re: Re: How do you ++ a fraction?
by tommyw (Hermit) on Aug 02, 2002 at 14:34 UTC

    Don't reinvoke on the same variable...

    (1++) ++ = 3 (0.004++) ++ = 0.006
    But...
    (1.99++) ++ = 3 (1.79++) ++ = 1.9 (1.009999++) ++ = 1.02

    --
    Tommy
    Too stupid to live.
    Too stubborn to die.

      That seems to be the desired behaviour. Since the numbe of decimal palces changes, I'd say that seems to be what is required.

      Would be simple enough to make a function to add a specific number to the "end".

      --
      Steve Marvell