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

#include <cmath>
#include <map>
#include <string>
using namespace std;
struct units {
    double y;
    map<int, char> m;
    units(int b) { y = log(b); }
    void add(char c) {
        m[int(m.size()) + 1] = c;
    }
    pair<int, char> get(double& x) {
        return *m.find(int(log(x) / y));
    }
};
units u {1'000};
u.add('k');
u.add('M');
u.add('G');
u.add('T');
pair p {u.get(a)};
a /= pow(1'000, p.first);
char x {p.second};
#include <cmath>
int y {int(log(a) / log(1'000))};
a /= pow(1'000, y);
char x {"kMGT"[y - 1]};
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 /= pow(1_000, si.ordinal() + 1);
String x = si.name();
import static java.lang.Math.log;
import static java.lang.Math.pow;
int y = (int) (log(a) / log(1_000));
a /= pow(1_000, y);
char x = "kMGT".charAt(y - 1);
function GetSIPrefix(AValue: Double): string;
const
  SIPrefixes: array[1..24] of String = ('Q','R','Y', 'Z','E','P','T','G','M','K','H','D','','d','c','m','µ','mc','n','p','f','a','z','y');
  SIFactors:  array[1..24] of Double = (1E+30,1E+27,1E+24, 1E+21, 1E+18, 1E+15, 1E+12, 1E+9, 1E+6, 1E+3,1E+2,1E+1,1,1E-1,1E-2,
var
  i: Integer;
begin
  Result := '';
  for i := 1 to 24 do
  begin
    if (Abs(AValue) >= SIFactors[i]) then
    begin
      Exit(SIPrefixes[i]);
    end;
  end;
end;
from math import log
from enum import Enum, auto, nonmember
class SI(Enum):
    k = 'kilo', auto()
    M = 'mega', auto()
    G = 'giga', auto()
    T = 'tera', auto()
    _y = nonmember(log(1_000))
    def __init__(self, s, y):
        self.s, self.y = s, y
    @classmethod
    def get(cls, a):
        i = log(a) // cls._y
        for x in cls:
            if x.y == i: return x
si = SI.get(a)
a /= 1_000 ** si.y
x = si.name
from math import log
y = int(log(a, 1_000))
a /= 1_000 ** y
x = 'kMGT'[y - 1]
m = {f'{a / 1e12} T': a > 999_999_999_999,
     f'{a /  1e9} G': a > 999_999_999,
     f'{a /  1e6} M': a > 999_999,
     f'{a /  1e3} k': a > 999,
     f'{a} ': ...}
s = next(k for k, v in m.items() if v)
x =  case a
  when 1e3... 1e6 ; "k"
  when 1e6... 1e9 ; "M"
  when 1e9... 1e12; "G"
  when 1e12...1e15; "T"
  else ""
end

New implementation...
< >
reilas