U
U
UnFox2018-02-21 00:42:57
PHP
UnFox, 2018-02-21 00:42:57

How to convert abbreviated numbers to regular ones?

There is a function that makes abbreviated numbers, for example 1000 = 1k.

function number_format_short( $n, $precision = 1 ) {
  if ($n < 999) {
    // 0 - 900
    $n_format = number_format($n, $precision);
    $suffix = '';
  } else if ($n < 999999) {
    // 0.9k-850k
    $n_format = number_format($n / 1000, $precision);
    $suffix = 'к';
  } else if ($n < 999999999) {
    // 0.9m-850m
    $n_format = number_format($n / 1000000, $precision);
    $suffix = 'кк';
  } else if ($n < 999999999999) {
    // 0.9b-850b
    $n_format = number_format($n / 1000000000, $precision);
    $suffix = 'ккк';
  } else {
    // 0.9t+
    $n_format = number_format($n / 1000000000000, $precision);
    $suffix = 'кккк';
  }
  // Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
  // Intentionally does not affect partials, eg "1.50" -> "1.50"
  if ( $precision > 0 ) {
    $dotzero = '.' . str_repeat( '0', $precision );
    $n_format = str_replace( $dotzero, '', $n_format );
  }
  return $n_format . $suffix;
}

How can I transfer them back now?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-02-21
@Stalker_RED

function convert_em_back($num) {
  $numeric = intval($num, 10);
  $suffix = preg_replace('/[0-9]/', '', $num);
  if (preg_match('/[^k]/', $suffix)) {
  	return false; // wrong format
  }
  return $numeric * pow(1000, strlen($suffix));
}

bonus: js solution (don't waste the good)
function раскукожитьОбратно(num) {
  let numeric = parseInt(num, 10)
  let suffix = num.replace(/[0-9]/, '')
  if (suffix.split('').some(char=>char!=='k')) {
  	return NaN // wrong format
  }
  return numeric * Math.pow(1000, suffix.length)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question