note 22519 deleted from function.round by didou
| From: | didou@php.net | Date: | Wed, 17 Sep 2003 01:02:18 +0000 |
| Subject: | note 22519 deleted from function.round by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-56602@lists.php.net to get a copy of this message | ||
Note Submitter: ken@popcornmonsters.com
----
I was looking for a way to convert a string into the common money format and I was looking around
and I found a script that added commas to a string and so I altered it to take a string and format
it into a common money format 1,234.56 here is the script.
// splits a string and inserts commas and puts it into
// the common Money format 1,234.56
// Taken from cwe7g's comma integer script
// Ken Cochane
// http://www.PopcornMonsters.com
// 06-20-01
// Version 1.0
function to_money($string)
{
//look for commas in the string and remove them.
$string = preg_replace("|\,|","",$string);
//split the string into two First and Second
// First is before decimal, second is after First.Second
$Full = split("[\.]",$string);
$Count = count($Full);
if($Count > 1)
{
$First = $Full[0];
$Second = $Full[1];
$NumCents = strlen($Second);
if($NumCents == 2)
{
//do nothing already at correct length
}
else if($NumCents < 2)
{
//add an extra zero to the end
$Second = $Second . "0";
}
else if($NumCents > 2)
{
//either string off the end digits or round up
// I say string everything but the first 3 digits and then round
// since it is rare that anything after 3 digits effects the round
// you can change if you need greater accurcy, I don't so I didn't
// write that into the code.
$Temp = substr($Second,0,3);
$Rounded = round($Temp,-1);
$Second = substr($Rounded,0,2);
}
}
else
{
//there was no decimal on the end so add to zeros
$First = $Full[0];
$Second = "00";
}
$length = strlen($First);
if( $length <= 3 )
{
//To Short to add a comma
$string = $First . "." . $Second;
return $string;
}
else
{
$loop_count = intval( ( $length / 3 ) );
$section_length = -3;
for( $i = 0; $i < $loop_count; $i++ )
{
$sections[$i] = substr( $First, $section_length, 3 );
$section_length = $section_length - 3;
}
$stub = ( $length % 3 );
if( $stub != 0 )
{
$sections[$i] = substr( $First, 0, $stub );
}
$Done = implode( ",", array_reverse( $sections ) );
$Done = $Done . "." . $Second;
return $Done;
}
}