ShortCode

How to Round any Numeric Value using a ShortCode

Sometimes we have numeric float values (like 1.38888) that display somewhere on our content, lets say when we display a Review Average count or else float number and perhaps we want to round that number up or down, by as many decimal places as we wish.

We could alter the core code that produces the number for us in the first place but sometimes that is not the best solution, perhaps we will need the precise float number somewhere else, and just want to display this one instance with a rounded value.

We can use a ShortCode to wrap our Float Number and round it. It also works of course with a ShortCode that is producing the Float Number. To start, register this ShortCode in your Theme’s functions.php File (or install ToolWine ShortCodes, which has the ShortCode included already):

function round_values_shortcode($atts, $content){
     $atts = shortcode_atts( 
         array(
             'round' => 2,
             'dir'   => PHP_ROUND_HALF_UP,
          ), 
         $atts, 
         'round_values' 
     );
     if( !is_numeric( $content ) ){     
         $rounded_value = 'You passed non-numeric values to the shortcode!'; 
     } 
     else{     
         $rounded_value = round($content, $atts['round'], $atts['dir']); 
     } 
     return $rounded_value;
 }
 add_shortcode( 'round_values', 'round_values_shortcode' );

Done that, we can use the ShortCode like so:

[round_values]9.139928[/round_values]

As we can see in the source code the ShortCode supports several attributes, being round and dir, to control both the amount of decimals to round to, and the direction to round to.
A word about the Direction to round to:

PHP_ROUND_HALF_UP Rounds val away from zero when it is half way there, making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN Rounds val towards zero when it is half way there, making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVEN Rounds val towards the nearest even value when it is half way there, making both 1.5 and 2.5 into 2.
PHP_ROUND_HALF_ODD Rounds val towards the nearest odd value when it is half way there, making 1.5 into 1 and 2.5 into 3.