Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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".

import java.text.ChoiceFormat;
String s = "0#files|1#file|1<files";
s = new ChoiceFormat(s).format(a);
s = "%,d %s".formatted(a, s);
import java.util.ArrayList;
import java.util.List;
class Unit {
    String s;
    interface F<T> { T f(int x); }
    record G(F x, F y) {}
    List<G> m = new ArrayList<>();
    Unit(String symbol) { s = symbol; }
    void cond(F x, F y) {
        m.add(new G(x, y));
    }
    String parse(int x) {
        for (G g : m)
            if ((boolean) g.x.f(x))
                return (String) g.y.f(x);
        return x + (' ' + s);
    }
}
Unit u = new Unit("files");
u.cond(x -> x == 1, x -> "1 file");
String s = u.parse(a);
String s = "file" + (a != 1 ? 's' : "");
s = "%,d %s".formatted(a, s);
import static java.text.MessageFormat.format;
String s = "0#files|1#file|1<files";
s = "{0,number,integer} {0,choice," + s + "}";
s = format(s, a);
const
  x: array[boolean] of string = ('file','files');
...
  s := format('%d %s',[a, x[Abs(a)>1]]));
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)
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
s = "#{a} #{x}#{a == 1 ? "" : "s"}"

New implementation...
< >
reilas