# include <config.h>
#endif
-#if HAVE_INTTYPES_H
-# include <inttypes.h>
-#endif
-
#include <sys/types.h>
#include <stdio.h>
# include <limits.h>
#endif
+#if HAVE_STRING_H
+# include <string.h>
+#else
+# include <strings.h>
+#endif
+
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
#include <argmatch.h>
#include <error.h>
-#include <xstrtoul.h>
+#include <xstrtol.h>
#include "human.h"
'Y' /* Yotta */
};
+/* Like human_readable_inexact, except always round to even. */
+char *
+human_readable (uintmax_t n, char *buf,
+ int from_block_size, int output_block_size)
+{
+ return human_readable_inexact (n, buf, from_block_size, output_block_size,
+ human_round_to_even);
+}
+
/* Convert N to a human readable format in BUF.
N is expressed in units of FROM_BLOCK_SIZE. FROM_BLOCK_SIZE must
- be positive.
+ be nonnegative.
If OUTPUT_BLOCK_SIZE is positive, use units of OUTPUT_BLOCK_SIZE in
the output number. OUTPUT_BLOCK_SIZE must be a multiple of
FROM_BLOCK_SIZE or vice versa.
+ Use INEXACT_STYLE to determine whether to take the ceiling or floor
+ of any result that cannot be expressed exactly.
+
If OUTPUT_BLOCK_SIZE is negative, use a format like "127k" if
possible, using powers of -OUTPUT_BLOCK_SIZE; otherwise, use
ordinary decimal format. Normally -OUTPUT_BLOCK_SIZE is either
than -OUTPUT_BLOCK_SIZE aren't modified. */
char *
-human_readable (uintmax_t n, char *buf,
- int from_block_size, int output_block_size)
+human_readable_inexact (uintmax_t n, char *buf,
+ int from_block_size, int output_block_size,
+ enum human_inexact_style inexact_style)
{
uintmax_t amt;
int base;
int to_block_size;
- int tenths;
+ int tenths = 0;
int power;
char *p;
1 means AMT.TENTHS < adjusted N < AMT.TENTHS + 0.05;
2 means adjusted N == AMT.TENTHS + 0.05;
3 means AMT.TENTHS + 0.05 < adjusted N < AMT.TENTHS + 0.1. */
- int rounding;
+ int rounding = 0;
if (output_block_size < 0)
{
{
int multiplier = from_block_size / to_block_size;
amt = n * multiplier;
- tenths = rounding = 0;
if (amt / multiplier != n)
{
return buf;
}
}
+ else if (from_block_size == 0)
+ amt = 0;
else
{
int divisor = to_block_size / from_block_size;
if (amt < 10)
{
- tenths += 2 < rounding + (tenths & 1);
-
- if (tenths == 10)
+ if (2 * (1 - (int) inexact_style)
+ < rounding + (tenths & (inexact_style == human_round_to_even)))
{
- amt++;
- tenths = 0;
+ tenths++;
+ rounding = 0;
+
+ if (tenths == 10)
+ {
+ amt++;
+ tenths = 0;
+ }
}
if (amt < 10)
{
*--p = '0' + tenths;
*--p = '.';
- tenths = 0;
+ tenths = rounding = 0;
}
}
}
- if (5 < tenths + (2 < rounding + (amt & 1)))
+ if (inexact_style == human_ceiling
+ ? 0 < tenths + rounding
+ : inexact_style == human_round_to_even
+ ? 5 < tenths + (2 < rounding + (amt & 1))
+ : /* inexact_style == human_floor */ 0)
{
amt++;