note 55316 deleted from function.is-numeric by crell
| From: | crell@php.net | Date: | Mon, 18 Apr 2022 14:58:01 +0000 |
| Subject: | note 55316 deleted from function.is-numeric by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218282@lists.php.net to get a copy of this message | ||
Note Submitter: namik at hub-cafe dot net
----
I needed a number_suffix function that takes numbers with thousand seperators (using number_format()
function). Note that this doesn't properly handle decimals.
Example:
<?= number_suffix('1,021') ?> returns: 1,021st
Also, increasing the range above the condition statements increases efficiency. That's almost
20% of the numbers between 0 and 100 that get to end early.
<?
function number_suffix($number)
{
// Validate and translate our input
if ( is_numeric($number) )
{
// Get the last two digits (only once)
$n = $number % 100;
} else {
// If the last two characters are numbers
if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
{
// Return the last one or two digits
$n = array_pop($matches);
} else {
// Return the string, we can add a suffix to it
return $number;
}
}
// Skip the switch for as many numbers as possible.
if ( $n > 3 && $n < 21 )
return $number . 'th';
// Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
switch ( $n % 10 )
{
case '1': return $number . 'st';
case '2': return $number . 'nd';
case '3': return $number . 'rd';
default: return $number . 'th';
}
}
?>