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 results", "1 result", or "1,000 results".

#include <string>
std::string s {a == 1 ? "file" : "files"};
import std.stdio;
import std.string: format;
string s = format("%d %s%s",a,x,a == 1 ? "" : "s");
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.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);
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(dict):
    def __init__(self, symbol):
        super().__init__()
        self.symbol = symbol
    def parse(self, x):
        for key in self:
            if key(x):
                return self[key].format(x)
        return f'{x} {self.symbol}'
unit = Unit('results')
unit[lambda n: n == 1] = '1 result'
unit[lambda n: n > 999] = '{:,} results'
s = unit.parse(a)
s = f'{a:,} {('result', 'results')[a != 1]}'
array = {
    lambda n: n == 1: '1 result',
    lambda n: n > 999: '{:,} results'
}
for key in array:
    if key(a):
        s = array[key].format(a)
        break
else:
    s = f'{a} results'
s = "#{a} #{x}#{a == 1 ? "" : "s"}"
let s = format!("{a} {x}{}",if a == 1 { "" } else { "s" });

New implementation...
reilas