KarlosFontana KarlosFontana - 3 months ago 7
PHP Question

PHP detect and remove unnecessary cent of price

For invoicing I want to determine if my total amount has an unnecessary cent. e.g. $5.01 or $5.51. If it detects the cent then I run an if statement to remove the cent: minus 0.01
eg.
Change

30.51
to
0.01
and give a warning message

and also

30.51
to
0.51


and also

30.51
to
1


Both come from a POST, so they are both PHP strings.

but no worries - i got it to work now thanks to dmayo

$pieces = explode(".", $TotalAmt);
echo "<br>p1:".$pieces[1]; // piece2
$p1 = $pieces[1];
$spl1 = str_split($p1);
$TAmttmp = 0;
//echo "<br>sp11:".$spl1; // error convert array to string
$TAmttmp = $spl1[0];
echo "<br>TAmttmp: with useless cent".$TAmttmp;
echo "<br>IT:".$IT;
if ($TAmttmp == 0.01) //so if there is 1 cent subtract the useless cent.
$TAmt = $TAmt - 0.01;
echo "<br>TAmt: with useless cent".$TAmt;
echo "<br>TAmt: without useless cent".$TAmt;

Answer

@Gumbo is right, we need to know the logic behind your conversions to provide a precise answer.

You could do an explode:

$var = explode('.',$_POST['val']);
$digits = $var[1]; // this will give you the digits after the decimal point

Now you can do what you need based on your logic.

You could also you use a substr() where you find the decimal point (is it always three places from the right?) and then grab the substring.

Not sure which would be more efficient.

Comments