November 26th, 2012, 02:13 AM
Issue with prices and number types
Alrighty gents. I be in another rutt.
Users will be able to create items on my site and each item will have a price. As is, it is listed as such:
Note the "." in between the two boxes. This represents a DOUBLE(8, 2) number type that can for example hold 123456.78.
echo "Price: $<input type='text' name='newDollars' maxlength='6' size='6' value='0' />.<input type='text' name='newCents' maxlength='2' size='1' value='00' /><br />";
The issue is with taking the input they give and converting it into a usable number that can be manipulated and displayed.
The code was one long line but i broke it up to make it readable. Essentially, dollars and cents are converted into an int to make sure that the user doesnt use decimals in the first or second box. These are then created into a float number where they are stored as a price.
if (is_numeric($dollars) && is_numeric($cents))
$dollars = (int)$dollars;
$cents = (int)$cents;
$price = (float)($dollars.".".$cents);
$error.= "Price must be a number.";
Dollars works fine, but cents has issues.
If the user enters "1." or just "1" in cents, it is converted to "10", but if the user enters ".1" or "01" it is also converted to "10".
I think the issue is with the number type ignoring 0's, but I can't seem to fix the issue.
Is there a solution? Is there a better way to input prices on items?
Any and all help is, as always, greatly appreciated.
November 26th, 2012, 04:15 AM
Sorry, I am not male, but hopefully what I have to say will help
$cents = sprintf("%02d", $cents)
November 26th, 2012, 06:24 PM
Sorry, when do i insert that code? in place of the (int)cents?
November 27th, 2012, 02:30 AM
Yes replace (int)cents with sprintf("%02d", $cents)
Originally Posted by ohmynexus
November 27th, 2012, 05:15 AM
And it looks to me as though this should represent a DECIMAL, not a DOUBLE!