xref: /titanic_44/usr/src/lib/libast/common/string/fmtnum.c (revision 1e4c938b57d1656808e4112127ff1dce3eba5314)
1 /***********************************************************************
2 *                                                                      *
3 *               This software is part of the ast package               *
4 *          Copyright (c) 1985-2010 AT&T Intellectual Property          *
5 *                      and is licensed under the                       *
6 *                  Common Public License, Version 1.0                  *
7 *                    by AT&T Intellectual Property                     *
8 *                                                                      *
9 *                A copy of the License is available at                 *
10 *            http://www.opensource.org/licenses/cpl1.0.txt             *
11 *         (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9)         *
12 *                                                                      *
13 *              Information and Software Systems Research               *
14 *                            AT&T Research                             *
15 *                           Florham Park NJ                            *
16 *                                                                      *
17 *                 Glenn Fowler <gsf@research.att.com>                  *
18 *                  David Korn <dgk@research.att.com>                   *
19 *                   Phong Vo <kpv@research.att.com>                    *
20 *                                                                      *
21 ***********************************************************************/
22 #pragma prototyped
23 /*
24  * Glenn Fowler
25  * AT&T Research
26  *
27  * return scaled number n
28  * string width is 5 chars or less
29  * if m>1 then n divided by m before scaling
30  */
31 
32 #include <ast.h>
33 
34 char*
35 fmtnum(register unsigned long n, int m)
36 {
37 	register int		i;
38 	register unsigned long	r;
39 	char*			buf;
40 	int			z;
41 
42 	char			suf[2];
43 
44 	if (m > 1)
45 	{
46 		r = n;
47 		n /= m;
48 		r -= n;
49 	}
50 	else
51 		r = 0;
52 	suf[1] = 0;
53 	if (n < 1024)
54 		suf[0] = 0;
55 	else if (n < 1024 * 1024)
56 	{
57 		suf[0] = 'k';
58 		r = ((n % 1024) * 100) / 1024;
59 		n /= 1024;
60 	}
61 	else if (n < 1024 * 1024 * 1024)
62 	{
63 		suf[0] = 'm';
64 		r = ((n % (1024 * 1024)) * 100) / (1024 * 1024);
65 		n /= 1024 * 1024;
66 	}
67 	else
68 	{
69 		suf[0] = 'g';
70 		r = ((n % (1024 * 1024 * 1024)) * 100) / (1024 * 1024 * 1024);
71 		n /= 1024 * 1024 * 1024;
72 	}
73 	if (r)
74 	{
75 		if (n >= 100)
76 			r = 0;
77 		else if (n >= 10)
78 		{
79 			i = 1;
80 			if (r >= 10)
81 				r /= 10;
82 		}
83 		else
84 			i = 2;
85 	}
86 	buf = fmtbuf(z = 8);
87 	if (r)
88 		sfsprintf(buf, z, "%lu.%0*lu%s", n, i, r, suf);
89 	else
90 		sfsprintf(buf, z, "%lu%s", n, suf);
91 	return buf;
92 }
93