Jump to content

[SOLVED] Outputting 2.00 and 1.30, rather than 2 and 1.3


johnny44

Recommended Posts

This converts fractions to decimals, rounded to two decimal places. But with fractions like 8/2 or 21/10, the outputs are 4 and 2.1, whereas I need 4.00 and 2.10. Need two decimal places always.

 

$numerator = 8;       // say
$denominator = 2;    // say 
$output = round ( ($numerator/$denominator) , 2 );
echo $output;

 

This outputs 4, but I need 4.00. I can get this done indirectly:

 

$array = explode( "." , $output );
$n = strlen( $array[1] );
if( $n == 0 ){ $output = $output . ".00"; }
elseif( $n == 1 ){ $output = $output . "0"; }
elseif($n == 2 ){ }

echo $output;

 

But this strikes me as being totally ridiculous. Is there a straightforward function I could use to ensure that output is always expressed to two decimal places? Numerator and denominator will vary, but are always positive integers.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.