Help needed to round-off a number

Steve Summit scs at adam.pika.mit.edu
Mon Jun 5 04:39:04 AEST 1989


In article <267 at ibd.BRL.MIL> heilpern at brl.arpa (Mark A. Heilpern (IBD) <heilpern>) writes:
>There is a relatively painless way to [truncate or round-off
>a number a certain decimal place]:
>2) multiply your original by 10^n
>2a) add (5 / 10^n) for round-up error
>3) truncate the fraction off of your answer
>4) divide this result by 10^n

If you have normalized the intermediate result by 10^n (in step 2)
then you round by adding one half, not 5/10^n.

Note that the method lets you round to a multiple of anything,
not necessarily limited to powers of ten.  (You may want to
subtract a half and/or use ceil() when rounding negative numbers,
though.)

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.lang.c mailing list