in reply to Round a fraction

How do you "add 1" to last digit of a fraction such that

     0.0012 gives  0.0013

     0.99999 gives  1

Update: rephrased question

Replies are listed 'Best First'.
Re: How do you ++ a fraction?
by marvell (Pilgrim) on Aug 02, 2002 at 14:09 UTC
    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

      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.

      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