Logo

Programming-Idioms

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

Idiom #364 Calculate the magnitude symbol for a value

Calculate the SI (International System of Units) prefix, x, of value a.

For example, 'k', 'M', 'G', 'T', etc.

https://en.wikipedia.org/wiki/Metric_prefix

import static java.lang.Math.log;
import static java.lang.Math.pow;
enum SI {
    k("kilo"),
    M("mega"),
    G("giga"),
    T("tera");
    String s;
    static double y = log(1_000);
    SI(String s) { this.s = s; }
    static SI get(double x) {
        int y = (int) (log(x) / SI.y);
        return values()[y - 1];
    }
}
SI si = SI.get(a);
a = a / pow(1_000, si.ordinal() + 1);
String x = si.name();

This is intended to work where a > 999.

New implementation...
< >
reilas