djjjozsi;10903966 wrote:Hello again.
i've tried this :
<?php
setlocale( LC_NUMERIC, 'en' );
function st( $num )
{
if ( is_numeric( $num ) OR is_float( $num ) )
{
return sprintf("%01.2f", $num);
}
else
{
$num = preg_replace( "/[^a-z0-9.]/", "", $num );
return sprintf("%01.2f", $num);
}
}
$num = "L 1,123.1"; //output 1123.10
print st( $num );
?>
djjj0zsi,
I think lee was wanting to know how your script worked, or more to the point what it is doing to correct his data.
Lee,
The set_locale line sets the PHP localised formatting to English currency format. The first if statement in the function then uses PHP's number validation routines to ensure there are NO non numeric characters in the number. If there are no non numerics, then the formated string print routine is used to return a floating point number with the decimal point in the correct place and return it.
If there are non numeric characters in the string, then the perl regular expression replace "preg_replace" uses a regular expression to remove the invalid chars from the entered string, and then uses the same string print format to return the formated number.
It's pretty simple, and pretty elegant.
As for adding commas into the output, then what you need to do is take the number with the decimal in, split it on the decimal, then counting from the end of the first part add a comma in every 3 chars. Somthing like this:
// Set the variable to out number with decimal in
$number = "1000000.50";
// Split the number on the decimal
$temp = explode(".",$number);
// We are working just on the major part
$majorpart = $temp[0];
// Set our variables, to initial values
$new = "";
$ccount = 0;
$start = strlen($majorpart)-1;
// Loop from the end of the string to the beginning.
for($i = $start;$i>-1;$i--)
{
// If we've added 3 chars already then add a comma
if($ccount == 3)
{
$new = $new . ",";
$ccount = 0;
}
// Add the next charachter in the string.
$new = $new . substr($majorpart,$i,1);
// Increment the comma counter.
$ccount ++;
}
// When we get here the number string will have a , every 3 chars
// it will however be back to front.
// What we do next is similar to above, but we simply just reverse the string.
$majorpart = "";
$start = strlen($new)-1;
for($i = $start;$i>-1;$i--)
{
$majorpart = $majorpart . substr($new,$i,1);
}
// Then we join the majorpart and the minor part back together, and put the decimal point back in.
$finalnumber = $majorpart.".".$temp[1];
To cover your last point, validating the input on the form will have to be done in javascript. I would recommend a toolkit such as "jQuery" or "Prototype" for this.
Cheers
Shawty