format numbers
by lovinglobo
JavaScript
/**
For which minimum delta do we choose what adjusment?
An adjustment is basically dividing the to be formatted value by the adjustment
value and adding the suffix, e.g. 1000 becomes 1k.
*/
const BIG_NUMBER_ADJUSTMENT_TABLE =[
{ minimum_delta: 100000000, suffix: 'm', adjustment: 1000000 },
{ minimum_delta: 100000, suffix: 'k', adjustment: 1000 },
];
/**
For which minimum delta do we choose what level of precision?
Any delta bigger than the smallest minimum_delta
will be formatted with scienitifc notation.
*/
const PRECISION_TABLE = [
{ minimum_delta: 1000, precision: 0 },
{ minimum_delta: 100, precision: 1 },
{ minimum_delta: 10, precision: 2 },
{ minimum_delta: 1, precision: 3 },
{ minimum_delta: 0.1, precision: 4 },
{ minimum_delta: 0.01, precision: 5 },
];
/**
Formats numbers based on the range that they are in, such that:
- for numbers in the same range always the same length of string will be returned
THIS IS NOT TRUE FOR POSITIVE NUMBERS!
- big numbers are adjusted downward using a suffix
- small numbers are set to a reasonable precision
- even smaller numbers will use scientific notation
*/
function formatNumber(min, max, value) {
const delta = Math.abs(max - min);
const adjustment_row = BIG_NUMBER_ADJUSTMENT_TABLE.find(a => delta >= a.minimum_delta);
const adjusted_value = adjustment_row ? value / adjustment_row.adjustment : value;
const adjusted_delta = adjustment_row ? delta / adjustment_row.adjustment : delta;
const suffix = adjustment_row ? adjustment_row.suffix : '';
const precision_row = PRECISION_TABLE.find(p => adjusted_delta >= p.minimum_delta);
if (!precision_row) {
return adjusted_value.toExponential(5);
} else {
return adjusted_value.toFixed(precision_row.precision) + suffix;
}
}
//////////////////
//// TESTING /////
//////////////////
const testValues = [
{ min: 0, max: 100000000, values: [0, 50000000, 912463000]},
{ min: 0, max: 10000000, values: [0, 5000000, 14646000]},
{ min: 0,...