Do you want to show your user a formatted number with comma and decimal? You come to the right place. Here's how.
function getNumberWithCommaAndDecimal( $given_number ){
// if the number given has decimals
if (strpos($given_number, '.') !== false) {
// count the number of decimals
$decimal_places = strlen( end( explode( ".", $given_number ) ) );
// get the formatted number
$result = number_format( $given_number, $decimal_places );
}
// the number given has no decimal places
// just get the formatted number with two decimal places
else{
$result = number_format( $given_number, 2 );
}
return $result;
}
// if the number given has decimals
if (strpos($given_number, '.') !== false) {
// count the number of decimals
$decimal_places = strlen( end( explode( ".", $given_number ) ) );
// get the formatted number
$result = number_format( $given_number, $decimal_places );
}
// the number given has no decimal places
// just get the formatted number with two decimal places
else{
$result = number_format( $given_number, 2 );
}
return $result;
}
How to use?
// will output 1,000,000.00
getNumberWithCommaAndDecimal(1000000);
getNumberWithCommaAndDecimal(1000000);