Forum Moderators: coopster

Message Too Old, No Replies

Stripping two Decimal Points

Should be an easy function - Cannot put my arms around it...

         

blaketar

1:05 am on Apr 11, 2007 (gmt 0)

10+ Year Member



I would simply like to throw an error if someone inserts a US price with two decimal points (23.000.00)

The function could strip the first decimal point and return 23,000.00 but feel it would be easier to point out the error to the end user inputting the price.

Any suggestions?

eelixduppy

2:38 am on Apr 11, 2007 (gmt 0)



You could do something like this:

if([url=http://www.php.net/manual/en/function.substr-count.php]substr_count[/url]($price,'.') > 1) {
echo 'Error - too many periods!';
} else {
echo 'Good price - proceed.';
}

borntobeweb

2:43 am on Apr 11, 2007 (gmt 0)

10+ Year Member



You can also use regex for this:


if(!preg_match('/^\\d*(\\.\\d{0,2})?$/', trim($input_value)))
echo "not a valid amount (999.99)";

camilord

11:45 am on Apr 11, 2007 (gmt 0)

10+ Year Member



<?php

$inputValue = '99.9999.9.999.99'; // -> input here..

$explodedValue = explode(".", $inputValue); // -> explode the value, separator would be the point
$countValueOfPeriod = sizeof($explodedValue); // -> count the array
$limit = $countValueOfPeriod - 1; // -> get the last number for the array element

if ($countValueOfPeriod > 2) // -> check if the array has a lot of periods
{
$lastValue = $countValueOfPeriod - 1;
$PeriodPlacement = $countValueOfPeriod - 2;
echo $countValueOfPeriod . "<br>";
for ($i = 0; $i <= $limit; $i++)
{
if ($i == 0)
{
$newValue .= $explodedValue[$i] . ',';
}
else
{
if ($i == $PeriodPlacement)
{
$newValue .= $explodedValue[$i] . '.';
} else {
if ($i!= $lastValue)
{
$newValue .= $explodedValue[$i] . ',';
}
else
{
$newValue .= $explodedValue[$i];
}
}
}
}
} else {
$newValue = $inputValue;
}

echo $newValue;

?>