Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!mit-eddie!uw-beaver!cornell!rochester!pt.cs.cmu.edu!cadre!pitt!unix.cis.pittsburgh.edu!jcbst3 From: jcbst3@unix.cis.pittsburgh.edu (James C. Benz) Newsgroups: comp.lang.c Subject: Re: Help rounding-off numbers (not using printf) Message-ID: <18226@unix.cis.pittsburgh.edu> Date: 31 May 89 17:32:36 GMT References: <2730@oregon.uoregon.edu> Reply-To: jcbst3@unix.cis.pittsburgh.edu (James C. Benz) Organization: Univ. of Pittsburgh, Comp & Info Sys Lines: 42 In article <2730@oregon.uoregon.edu> michelbi@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@unix.cis.pittsburgh.edu If a modem University of Pittsburgh answers, UCIR (412) 648-5930 hang up!