Help rounding-off numbers (not using printf)

James C. Benz jcbst3 at unix.cis.pittsburgh.edu
Thu Jun 1 03:32:36 AEST 1989


In article <2730 at oregon.uoregon.edu> michelbi at oregon.uoregon.edu (Michel Biedermann) writes:
>Is there a C function (user defined or primitive (?)) that will let me
>truncate or round-off a number UP TO a certain decimal place.  For example
>transforming .567 into .6 or -1.502 into -1.5 (i.e. N = round(.567) would
>set N to .6.  I do not want to simply print a rounded-off number but be
>able to use it as well.
> 
have you tried round(N+.5)-.5?  I seem to remember from a *really* elementary
CS course many moons ago that this is the way to do it.  I haven't tried it
or even thought about it too much, but it seems like it should work.  
Lets see,
	.567 + .5 = 1.067
	round(1.067) = 1.0
	1.0 - .5 = .5

Hmm, that's not right is it?

How about round(N+.5)-.4?
	-1.502 + .5 = -1.002
	round(-1.002) = -1.
	-1 - .4 = -1.4

Grr.  How about
	if (N > 0)
		round(N+.5)-.4
	else
		round(N+.5)-.5

	.567 +.5 = 1.067
	round(1.067) = 1.0
	1.0 - .4 = .6

	-1.502 +.5 = -1.002
	round(-1.002)=-1.
	-1. - .5 = -1.5

Seems right, but will it always work?

-- 
Jim Benz 		     jcbst3 at unix.cis.pittsburgh.edu     If a modem 
University of Pittsburgh					 answers,
UCIR			     (412) 648-5930			 hang up!



More information about the Comp.lang.c mailing list