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.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
class Unit {
    String s;
    interface F<T> { T f(int x); }
    Map<F, F> m = new LinkedHashMap<>();
    Unit(String s) { this.s = s; }
    void cond(F x, F y) { m.put(x, y); }
    String parse(int x) {
        for (Entry<F, F> t : m.entrySet())
            if ((boolean) t.getKey().f(x))
                return (String) t.getValue().f(x);
        return x + " " + s;
    }
}
Unit u = new Unit("files");
u.cond(x -> x == 1, x -> "1 file");
String s = u.parse(a);
import java.text.ChoiceFormat;
String s = "0#files|1#file|1<files";
s = new ChoiceFormat(s).format(a);
s = "%,d %s".formatted(a, s);
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);
#include <string>
std::string s {a == 1 ? "file" : "files"};
const
  x: array[boolean] of string = ('file','files');
...
  s := format('%d %s',[a, x[Abs(a)>1]]));
class Unit:
    def __init__(self, x):
        self.s, self.m = x, {}
    def cond(self, x, y):
        self.m[x] = 'f' + repr(y)
    def parse(self, x):
        m = self.m.items()
        g = (eval(v) for k, v in m if k(x))
        return next(g, f'{x} {self.s}')
x = Unit('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 = (lambda: a == 1, '1 file'), \
    (lambda: a > 999, '{a:,} files')
i = (eval('f' + repr(v)) for k, v in x if k())
s = next(i, f'{a} files')
s = "#{a} #{x}#{a == 1 ? "" : "s"}"

New implementation...
< >
reilas