michelbi@oregon.uoregon.edu (Michel Biedermann) (05/20/89)
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. Thanks a lot for the help... Michel Biedermann U. of Oregon
rob@phavl.UUCP (Robert Ransbottom) (05/21/89)
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 Seems unlikely, consider the vagaries of this with binary representation and decimal conceptualization. Printf() was a good suggestion. Look at sprintf to print to a string, and strtod to convert it back. WARNING: This should do the trick, but again the result is not as straight-forward as you _might_ think. Hope this helps. rob kill( blair, SIGKILL) -- ...!uunet!phavl!rob Robert Ransbottom
kremer@cs.odu.edu (Lloyd Kremer) (05/22/89)
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. I believe the function "ceil" is the most mathematically rigorous choice. It rounds up (toward positive infinity) to the nearest integer equal to or greater than the given number. extern double ceil(double); /* Round up to one decimal precision */ double num, result; result = ceil(10.0 * num) / 10.0; -- Lloyd Kremer Brooks Financial Systems ...!uunet!xanth!brooks!lloyd Have terminal...will hack!
jcbst3@unix.cis.pittsburgh.edu (James C. Benz) (06/01/89)
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!