Commerce
|
|
|
|
<?php // splits a string and inserts commas and the correct cents to make the common Money Format 1,234.56
// Used code from cwe7g's comma integer script version 1.0
// Ken Cochrane
// http://www.PopcornMonsters.com
// 06-20-2002
// Version 1.1
// Whats new in Version 1.1
// Added support for negative numbers
function to_money($string)
{
$Negative = 0;
//check to see if number is negative
if(preg_match("/^-/",$string))
{
//setflag
$Negative = 1;
//remove negative sign
$string = preg_replace("|-|","",$string);
}
//look for commas in the string and remove them.
$string = preg_replace("|,|","",$string);
// split the string into two parts First and Second
// First is before decimal, second is after. format = 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
//combine the first part and the second.
$string = $First . "." . $Second;
if($Negative == 1)
{
$string = "-" . $string;
}
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;
if($Negative == 1)
{
$Done = "-" . $Done;
}
return $Done;
}
} ?>
|
|
|
Usage Example
|
$string=1234.5612;
$Money = to_money($string);
print("$Money");
//Prints out 1,234.56
|
|
|
Rate This Script
|
|
|
|