Logo

Programming-Idioms

  • C
  • Python

Idiom #358 Format a value in unit notation

Create the end-user text, s, specifying the value a, in units of x.

For example, "0 files", "1 file", or "1,000 files".

class Unit:
    def __init__(self, symbol):
        self.s, self.a = symbol, []
    def cond(self, x, y):
        self.a.append((x, 'f' + repr(y)))
    def parse(self, x):
        for a, b in self.a:
            if a(x): return eval(b)
        else: return f'{x} {self.s}'
x = Unit('files')
x.cond(lambda x: not x, '0 files')
x.cond(lambda x: x == 1, '1 file')
x.cond(lambda x: x > 999, '{x:,} files')
s = x.parse(a)

This routine can be used to parse a unit-system as well, e.g., 'B', 'kB', 'MB', etc.
s = f'{a:,} {('file', 'files')[a != 1]}'
x = {
    f'{a / 1e9} GB': a > 999_999_999,
    f'{a / 1e6} MB': a > 999_999,
    f'{a / 1e3} kB': a > 999,
    f'{a} B': True,
}
for k, v in x.items():
    if v:
        s = k
        break
import java.text.ChoiceFormat;
String s = "0#files|1#file|1<files";
s = new ChoiceFormat(s).format(a);
s = "%,d %s".formatted(a, s);

New implementation...
< >
reilas