1 /////////////////////////////////////////////////////////////////////////
2 // ftos.cc
3 //
4 // Copyright (c) 1996-2003 Bryce W. Harrington [bryce at osdl dot org]
5 //
6 //-----------------------------------------------------------------------
7 // License: This code may be used by anyone for any purpose
8 // so long as the copyright notices and this license
9 // statement remains attached.
10 //-----------------------------------------------------------------------
11 // This routine rounds a double using the "rounding rule", as expressed
12 // in _Advanced Engineering Mathematics_ by Erwin Kreyszig, 6th ed.,
13 // John Wiley & Sons, Inc., 1988, page 945.
14 //
15 // Discard the (k+1)th and all subsequent decimals.
16 // (a) If the number thus discarded is less than half a unit in the
17 // kth place, leave the kth decimal unchanged ("rounding down")
18 // (b) If it is greater than half a unit in the kth place, add one
19 // to the kth decimal ("rounding up")
20 // (c) If it is exactly half a unit, round off to the nearest *even*
21 // decimal.
22 // Example: Rounding off 3.45 and 3.55 by one decimal gives 3.4 and
23 // 3.6, respectively.
24 // Rule (c) is to ensure that in discarding exactly half a decimal,
25 // rounding up and rounding down happens about equally often,
26 // on the average.
27 ///////////////////////////////////////////////////////////////////////
28 #include <math.h>
30 double rround(double x)
31 {
32 double xlow = floor(x);
33 if (x - xlow != 0.5000)
34 return floor(x + 0.5000);
35 else if ( floor(x/2.0) == xlow/2.0)
36 return xlow;
37 else
38 return xlow++;
39 }
41 // This version allows rounding to a specific digit
42 double rround(double x, int k)
43 {
44 if (k==0) return rround(x);
45 else return rround(x*pow(10,k)) / pow(10,k);
46 }