function restyle_text($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
if($input_count != '0'){
if($input_count == '1'){
return substr($input, +4).'k';
} else if($input_count == '2'){
return substr($input, +8).'mil';
} else if($input_count == '3'){
return substr($input, +12).'bil';
} else {
return;
}
} else {
return $input;
}
}
This is the code I have, I thought it was working. apparently not.. can someone help since I can't figure this out.
Try this:
http://codepad.viper-7.com/jfa3uK
function restyle_text($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
if($input_count != '0'){
if($input_count == '1'){
return substr($input, 0, -4).'k';
} else if($input_count == '2'){
return substr($input, 0, -8).'mil';
} else if($input_count == '3'){
return substr($input, 0, -12).'bil';
} else {
return;
}
} else {
return $input;
}
}
Basically, I think you're using the substr() wrong.
Here's a generic way to do this that doesn't require you to use number_format or do string parsing:
function formatWithSuffix($input)
{
$suffixes = array('', 'k', 'm', 'g', 't');
$suffixIndex = 0;
while(abs($input) >= 1000 && $suffixIndex < sizeof($suffixes))
{
$suffixIndex++;
$input /= 1000;
}
return (
$input > 0
// precision of 3 decimal places
? floor($input * 1000) / 1000
: ceil($input * 1000) / 1000
)
. $suffixes[$suffixIndex];
}
And here's a demo showing it working correctly for several cases.
I re-wrote the function to use the properties of numbers rather than playing with strings.
That should be faster.
Let me know if I missed any of your requirements:
function restyle_text($input){
$k = pow(10,3);
$mil = pow(10,6);
$bil = pow(10,9);
if ($input >= $bil)
return (int) ($input / $bil).'bil';
else if ($input >= $mil)
return (int) ($input / $mil).'mil';
else if ($input >= $k)
return (int) ($input / $k).'k';
else
return (int) $input;
}
I do not want to spoil the moment... but I think this is a little more simplified.
Just improving #Indranil answer
e.g.
function comp_numb($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
$arr = array(1=>'K','M','B','T');
if(isset($arr[(int)$input_count]))
return substr($input,0,(-1*$input_count)*4).$arr[(int)$input_count];
else return $input;
}
echo comp_numb(1000);
echo '<br />';
echo comp_numb(1000000);
echo '<br />';
echo comp_numb(1000000000);
echo '<br />';
echo comp_numb(1000000000000);
Or you can too use library How it works is here
Juste install composer require stillat/numeral.php and
<?php
require_once __DIR__.'/vendor/autoload.php';
$formatter = new Stillat\Numeral\Numeral;
$formatter->setLanguageManager(new Stillat\Numeral\Languages\LanguageManager);
$formatter->format(1532, '0a,0'); //Affiche 1.5K
Related
I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..
I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.
Here the code:-
<?php
function numberOfR($string1)
{
for($i=0;$i <strlen($string1);$i++)
{
if($string1[$i]!='K')
{
$count++;
}
}
return $count;
}
$return_value= numberOfR("RKKRK");
echo "R's count is:";
echo $return_value;
?>
<?php
function getLongetSegment($string) {
$currentSegmentChar='';
$currentSegment="";
$biggestSegment="";
$current_length=0;
$biggest_length=0;
for($i=0;$i<strlen($string);$i++) {
$char = $string[$i];
if($char != $currentSegmentChar || $currentSegmentChar == '') {
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
$biggest_length = $current_length;
}
$currentSegmentChar = $char;
$currentSegment = $char;
$current_length = 1;
}
elseif($currentSegmentChar != '') {
$currentSegment .= $char;
$current_length++;
}
}
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
}
return array("string" => $biggestSegment,"length" => $biggest_length);
}
print_r(getLongetSegment("RKKRGGG"));
?>
Result: GGG
You can use preg_match_all over here as
preg_match_all('/(.)\1+/i','RKKRRRRK',$res);
usort($res[0],function($a,$b){
return strlen($b) - strlen($a);
});
echo $res[0][0];
Not sure if I understood this quite right. Something like this:
function maxCharSequece($string1)
{
$maxSeq = $seq = 0;
$maxChar = $lastChar = null;
for( $i = 0; $i < strlen($string1); $i++ )
{
$c = $string1[$i];
if (!$lastChar) $lastChar = $c;
if ( $lastChar == $c ){
if ( ++$seq > $maxSeq ) $maxChar = $lastChar;
}
else {
$maxSeq = $seq;
$seq = 0;
}
}
return $maxChar;
}
You can use preg_replace_callback to receive all continuous segments and select the longest
$sq = '';
preg_replace_callback('/(.)\1+/',
function ($i) use (&$sq) {
if(strlen($i[0]) > strlen($sq)) $sq = $i[0];
}, $str);
echo $sq . " " . strlen($sq);
This question already has answers here:
Shorten long numbers to K/M/B?
(14 answers)
Closed 8 years ago.
I need to show a page views value in the format of 1K of equal to one thousand, or 1.1K, 1.2K, 1.9K etc, if its not an even thousands, otherwise if under a thousand, display normal 500, 100, 250 etc, using PHP to format the number?
I'm using:--
function count_number($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000000) return round(($n/1000000000000),1).'T';
else if($n>1000000000) return round(($n/1000000000),1).'G';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
BUT it does not work correctly...
If my page visted 2454 times, it shows 2.5k and if 2990, it shows 3k...
How o fix that problem??
I want to SHOW Like --> if page visited 2454 -> how to display 2.4k and if 2990 -> 2.9k, if 3000 -> 3k etc
Plz help me...
Thanks # MonkeyZeus
Now itz DONE...
function kilo_mega_giga($n) {
if($n >= 1000 && $n < 1000000)
{
if($n%1000 === 0)
{
$formatted = ($n/1000);
}
else
{
$formatted = substr($n, 0, -3).'.'.substr($n, -3, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'k';
} else
if($n >= 1000000 && $n < 1000000000)
{
if($n%1000000 === 0)
{
$formatted = ($n/1000000);
}
else
{
$formatted = substr($n, 0, -6).'.'.substr($n, -6, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'M';
} else
if($n >= 1000000000 && $n < 1000000000000)
{
if($n%1000000000 === 0)
{
$formatted = ($n/1000000000);
}
else
{
$formatted = substr($n, 0, -9).'.'.substr($n, -9, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'G';
} else
if($n >= 0 && $n < 1000)
{
$formatted= $n;
}
return $formatted;
}
You can use this to calculate thousands. You can use this formula to figure out the formula for millions as well.
$n = 2000;
$formatted = '';
if($n >= 1000 && $n < 1000000)
{
if($n%1000 === 0)
{
$formatted = ($n/1000);
}
else
{
$formatted = substr($n, 0, -3).'.'.substr($n, -3, -2);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'k';
}
echo $formatted;
Also, please use curly braces, ALWAYS. Future you will thank present you.
What about number greater than 10000
function facebookFormattter($digit) {
if ($digit >= 1000000000) {
return round($digit/ 1000000000, 1). 'G';
}
if ($digit >= 1000000) {
return round($digit/ 1000000, 1).'M';
}
if ($digit >= 1000) {
return round($digit/ 1000, 1). 'K';
}
return $digit;
}
For example $num='7,57,800';
How can I display the value of $number as 7.57 Lakhs?
Here's the function:
function formatInIndianStyle($num){
$pos = strpos((string)$num, ".");
if ($pos === false) {
$decimalpart="00";
}
if (!($pos === false)) {
$decimalpart= substr($num, $pos+1, 2); $num = substr($num,0,$pos);
}
if(strlen($num)>3 & strlen($num) <= 12){
$last3digits = substr($num, -3 );
$numexceptlastdigits = substr($num, 0, -3 );
$formatted = makeComma($numexceptlastdigits);
$stringtoreturn = $formatted.",".$last3digits.".".$decimalpart ;
}elseif(strlen($num)<=3){
$stringtoreturn = $num.".".$decimalpart ;
}elseif(strlen($num)>12){
$stringtoreturn = number_format($num, 2);
}
if(substr($stringtoreturn,0,2)=="-,"){
$stringtoreturn = "-".substr($stringtoreturn,2 );
}
return $stringtoreturn;
}
function makeComma($input){
if(strlen($input)<=2)
{ return $input; }
$length=substr($input,0,strlen($input)-2);
$formatted_input = makeComma($length).",".substr($input,-2);
return $formatted_input;
}
Check this plugin- http://archive.plugins.jquery.com/project/numberformatter
Here's an example of how you'd use this plugin.
$("#salary").blur(function(){
$(this).parseNumber({format:"#,###.00", locale:"us"});
$(this).formatNumber({format:"#,###.00", locale:"us"});
});
Just change the locale..
For more example and information visit- http://code.google.com/p/jquery-numberformatter/
My example source: http://code.google.com/p/jquery-numberformatter/
Hope this helps :)
Here is another solution just for reference:
<?php
# Output easy-to-read numbers
# by james at bandit.co.nz
function bd_nice_number($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
else if($n>1000000000) return round(($n/1000000000),1).' billion';
else if($n>1000000) return round(($n/1000000),1).' million';
else if($n>1000) return round(($n/1000),1).' thousand';
return number_format($n);
}
?>
<?php //Credits are going to: #Niet-the-Dark-Absol
function indian_number_format($num){
$num=explode('.',$num);
$dec=(count($num)==2)?'.'.$num[1]:'.00';
$num = (string)$num[0];
if( strlen($num) < 4) return $num;
$tail = substr($num,-3);
$head = substr($num,0,-3);
$head = preg_replace("/\B(?=(?:\d{2})+(?!\d))/",",",$head);
return $head.",".$tail.$dec;
}
?>
Question: stackoverflow.com/questions/10042485
I am looking for something like this: How to generate a regular expression at runtime to match a numeric range but written in php.
Answering your question here, since comments are horrible for code blocks. I wouldn't translate a statement like that directly, as it's nearly unreadable. It's far easier to pick apart like this:
if ($n == $m) { // max/min ranges are the same, so just look for that number of characters
$format = "\{$n\}"; // {n}
} elseif ($n == 1) { // min range is 1, so use the max
$format = "\{1,$m\}"; // {1,m}
} else { // arbitary n->m range
$format = "\{$n,$m\}"; // {n,m}
}
It CAN be done in PHP as a ternary, it's just as illegible/impossible to debug, though:
$format = ($n == $m) ? "\{$n\}" : (($n == 1) ? "\{1,$m\}" : "\{$n,$m\}");
I think this should work:
class NumericRangeRegexGenerator {
private function baseRange($num,$up, $leading1) {
$c = $num[0];
$low = $up ? $c : ($leading1 ? '1' : '0');
$high = $up ? '9': $c;
if (strlen($num) == 1)
return $this->charClass($low, $high);
$re = $c . "(" . $this->baseRange(substr($num,1), $up, false) . ")";
if ($up) $low++; else $high--;
if ($low <= $high)
$re .= "|" . $this->charClass($low, $high) . $this->nDigits(strlen($num) - 1);
return $re;
}
private function charClass($b, $e) {
//String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e); (in java)
if ($b == $e) {
$format = $b;
} elseif ($e-$b>1) {
$format = '['.$b.'-'.$e.']';
} else {
$format = '['.$b.$e.']';
}
return $format;
}
private function nDigits($n, $m=null) {
//String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m) (in java)
if($m===null){
nDigits($n, $n);
}
if ($n == $m) { // max/min ranges are the same, so just look for that number of characters
$format = "\{$n\}"; // {n}
} elseif ($n == 1) { // min range is 1, so use the max
$format = "\{1,$m\}"; // {1,m}
} else { // arbitary n->m range
$format = "\{$n,$m\}"; // {n,m}
}
return "[0-9]" . $format;
}
private function eqLengths($from, $to) {
$fc = $from[0];
$tc = $to[0];
if (strlen($from) == 1 && strlen($to) == 1)
return $this->charClass($fc, $tc);
if ($fc == $tc)
return $fc . "(".$this->rangeRegex(substr($from,1), substr($to,1)).")";
$re = $fc . "(" . $this->baseRange(substr($from,1), true, false) . ")|"
. $tc . "(" . $this->baseRange(substr($to,1), false, false) . ")";
if (++$fc <= --$tc)
$re .= "|" . $this->charClass($fc, $tc) . $this->nDigits(strlen($from) - 1);
return $re;
}
private function nonEqLengths($from, $to) {
$re = $this->baseRange($from,true,false) . "|" . $this->baseRange($to,false,true);
if (strlen($to) - strlen($from) > 1)
$re .= "|[1-9]" . $this->nDigits(strlen($from), strlen($to) - 2);
return $re;
}
public function rangeRegex($n, $m) {
return strlen($n) == strlen($m) ? $this->eqLengths($n, $m) : $this->nonEqLengths($n, $m);
}
}
Ok so I am trying to turn my hit counter to round thousands to a single digit too display 3 thousand hits as 3K for example, like the Facebook Share and Twitter Tweet Buttons do. Here is my code. Any idea what I am doing wrong?
$postresultscount = (($resultscount) ? $resultscount->sumCount : 1);
$k = 1000;
$L = '';
if ($postresultscount > $k) {
$echoxcount = round($postresultscount/$k);
$L = 'K';
} else if ($postresultscount == $k) {
$echoxcount = 1;
$L = 'K';
} else {
$echoxcount = $postresultscount;
}
echo 'document.write("'.$echoxcount.' '.$L.'")';
Here comes a PHP function to format numbers to nearest thousands such as Kilos, Millions, Billions, and Trillions with comma
Function
function thousandsCurrencyFormat($num) {
if($num>1000) {
$x = round($num);
$x_number_format = number_format($x);
$x_array = explode(',', $x_number_format);
$x_parts = array('k', 'm', 'b', 't');
$x_count_parts = count($x_array) - 1;
$x_display = $x;
$x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '');
$x_display .= $x_parts[$x_count_parts - 1];
return $x_display;
}
return $num;
}
Output
thousandsCurrencyFormat(3000) - 3k
thousandsCurrencyFormat(35500) - 35.5k
thousandsCurrencyFormat(905000) - 905k
thousandsCurrencyFormat(5500000) - 5.5m
thousandsCurrencyFormat(88800000) - 88.8m
thousandsCurrencyFormat(745000000) - 745m
thousandsCurrencyFormat(2000000000) - 2b
thousandsCurrencyFormat(22200000000) - 22.2b
thousandsCurrencyFormat(1000000000000) - 1t (1 trillion)
Resources
https://code.recuweb.com/2018/php-format-numbers-to-nearest-thousands/
function shortNumber($num)
{
$units = ['', 'K', 'M', 'B', 'T'];
for ($i = 0; $num >= 1000; $i++) {
$num /= 1000;
}
return round($num, 1) . $units[$i];
}
I adapted this one from a function created to display bytes in human readable form by bashy here:
https://laracasts.com/discuss/channels/laravel/human-readable-file-size-and-time
a bit better than the post of Yuki
if ($value > 999 && $value <= 999999) {
$result = floor($value / 1000) . ' K';
} elseif ($value > 999999) {
$result = floor($value / 1000000) . ' M';
} else {
$result = $value;
}
Question is 8 years old but each time I see an answer that contains an else statement, I think it can be done in a better (cleaner) way.
<?php
if (!function_exists('format_number_in_k_notation')) {
function format_number_in_k_notation(int $number): string
{
$suffixByNumber = function () use ($number) {
if ($number < 1000) {
return sprintf('%d', $number);
}
if ($number < 1000000) {
return sprintf('%d%s', floor($number / 1000), 'K+');
}
if ($number >= 1000000 && $number < 1000000000) {
return sprintf('%d%s', floor($number / 1000000), 'M+');
}
if ($number >= 1000000000 && $number < 1000000000000) {
return sprintf('%d%s', floor($number / 1000000000), 'B+');
}
return sprintf('%d%s', floor($number / 1000000000000), 'T+');
};
return $suffixByNumber();
}
}
dump(format_number_in_k_notation(123)); // "123"
dump(format_number_in_k_notation(73000)); // "73K+"
dump(format_number_in_k_notation(216000)); // "216K+"
dump(format_number_in_k_notation(50400123)); // "50M+"
dump(format_number_in_k_notation(12213500100600)); // "12T+"
die;
function print_number_count($number) {
$units = array( '', 'K', 'M', 'B');
$power = $number > 0 ? floor(log($number, 1000)) : 0;
if($power > 0)
return #number_format($number / pow(1000, $power), 2, ',', ' ').' '.$units[$power];
else
return #number_format($number / pow(1000, $power), 0, '', '');
}
My func
function numsize($size,$round=2){
$unit=['', 'K', 'M', 'G', 'T'];
return round($size/pow(1000,($i=floor(log($size,1000)))),$round).$unit[$i];
}
Use floor instead of round if you want 3500 to round down to 3 K.
Otherwise, your code works, albeit problematically. Try this:
if ($postresultscount > 1000) {
$result = floor($postresultscount / 1000) . 'K';
} else {
$result = $postresultscount;
}
echo 'document.write("' . $result . '")";
It also appears you're writing JavaScript using PHP—take care.
This is a modified version with k and m lowercase and show one decimal place for milllions.
<?php
if ($value > 999 && $value <= 999999) {
$result = floor($value / 1000) . 'k';
} elseif ($value > 999999) {
$result = number_format((float)$value , 1, '.', '')/1000000 . 'm';
} else {
$result = $value;
}
?>
Several good answers have already been given to this particularly old question, however, most are too simple for my taste or not easy to extend for more units, so here's what I use:
# The function that returns a number formatted as a string in thousands, millions etc.
public static function getNumberAbbreviation (Int $number, Int $decimals = 1) : String {
# Define the unit size and supported units.
$unitSize = 1000;
$units = ["", "K", "M", "B", "T"];
# Calculate the number of units as the logarithm of the absolute value with the
# unit size as base.
$unitsCount = ($number === 0) ? 0 : floor(log(abs($number), $unitSize));
# Decide the unit to be used based on the counter.
$unit = $units[min($unitsCount, count($units) - 1)];
# Divide the value by unit size in the power of the counter and round it to keep
# at most the given number of decimal digits.
$value = round($number / pow($unitSize, $unitsCount), $decimals);
# Assemble and return the string.
return $value . $unit;
}
I created my own method inspired by Twitter.
Function:
function legibleNumb($numb, $lang = 'en') {
if ($lang == 'tr') { // Usage with commas in Turkish
if ($numb >= 1000000) { // Million
if (strstr(round(number_format($numb,0,',','.'),1),'.')) {
$legibleNumb = number_format(round(number_format($numb,0,',','.'),1),1,',','.') . ' Mn';
} else {
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' Mn';
}
} elseif ($numb >= 100000 && $numb < 1000000) { // One hundred thousand
$legibleNumb = round(number_format($numb,0,',','.'),0) . ' B';
} elseif ($numb >= 10000 && $numb < 100000) { // Ten thousand
if (strstr(round(number_format($numb,0,',','.'),1),'.')) {
$legibleNumb = number_format(round(number_format($numb,0,',','.'),1),1,',','.') . ' B';
} else {
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' B';
}
} else {
$legibleNumb = number_format($numb,0,',','.');
}
} else { // Dotted usage in English
if ($numb >= 1000000) { // Million
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' M';
} elseif ($numb >= 100000 && $numb < 1000000) { // One hundred thousand
$legibleNumb = round(number_format($numb,0,',','.'),0) . ' K';
} elseif ($numb >= 10000 && $numb < 100000) { // Ten thousand
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' K';
} else {
$legibleNumb = number_format($numb,0,',','.');
}
}
return $legibleNumb;
}
Usage:
echo legibleNumb(9999999,'en');
echo legibleNumb(9999999,'tr');
echo legibleNumb(54669,'en');
echo legibleNumb(54669,'tr');
echo legibleNumb(5466,'en');
echo legibleNumb(5466,'tr');
Results:
10 M
10 Mn
54.7 K
54,7 B
5.466
5.466
You can try it here and check out sample usages: https://glot.io/snippets/eljyd9ssjx
if ($postresultscount > 999999) {
$postresultscount = floor($postresultscount / 1000000) . ' M';
}
elseif ($postresultscount > 999) {
$postresultscount = floor($postresultscount / 1000) . ' K';
}
echo $postresultscount;
This questuion have the same goal as this question in here Shorten long numbers to K/M/B?
Reference:
https://gist.github.com/RadGH/84edff0cc81e6326029c
Try this code:
function number_format_short( $n, $precision = 1 ) {
if ($n < 900) {
// 0 - 900
$n_format = number_format($n, $precision);
$suffix = '';
} else if ($n < 900000) {
// 0.9k-850k
$n_format = number_format($n / 1000, $precision);
$suffix = 'K';
} else if ($n < 900000000) {
// 0.9m-850m
$n_format = number_format($n / 1000000, $precision);
$suffix = 'M';
} else if ($n < 900000000000) {
// 0.9b-850b
$n_format = number_format($n / 1000000000, $precision);
$suffix = 'B';
} else {
// 0.9t+
$n_format = number_format($n / 1000000000000, $precision);
$suffix = 'T';
}
// 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;
}
The code above create a function to convert the numbers. To use this function later just call it like in the code below:
// Example Usage:
number_format_short(7201); // Output: 7.2k
Rounding up, not accounting for any abbreviations above 'k' or thousands, showing one decimal place.
function numToKs($number) {
if ($number >= 1000) {
return number_format(($number / 1000), 1) . 'k';
} else {
return $number;
}
}
numToKs(1) = 1
numToKs(111) = 111
numToKs(999) = 999
numToKs(1000) = "1.0k"
numToKs(1499) = "1.5k"
numToKs(1500) = "1.5k"
numToKs(1501) = "1.5k"
numToKs(1550) = "1.6k"
numToKs(11501) = "11.5k"
numToKs(1000000000) = "1,000,000.0k"
numToKs(1234567890) = "1,234,567.9k"