#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0

    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:

    PHP Code:
    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 />"
    Note the "." in between the two boxes. This represents a DOUBLE(8, 2) number type that can for example hold 123456.78.

    The issue is with taking the input they give and converting it into a usable number that can be manipulated and displayed.

    PHP Code:
    if (is_numeric($dollars) && is_numeric($cents))
                    {
                        
    $dollars = (int)$dollars;
                        
    $cents = (int)$cents;
                        
    $price = (float)($dollars.".".$cents);
                    }
                    else
                    {
                        
    $error.= "Price must be a number.";
                    } 
    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.

    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.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    119
    Rep Power
    33
    Sorry, I am not male, but hopefully what I have to say will help

    Try
    PHP Code:
    $cents sprintf("%02d"$cents
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    Sorry, when do i insert that code? in place of the (int)cents?
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    119
    Rep Power
    33
    Originally Posted by ohmynexus
    Sorry, when do i insert that code? in place of the (int)cents?
    Yes replace (int)cents with sprintf("%02d", $cents)
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Mar 2008
    Posts
    1,928
    Rep Power
    378
    And it looks to me as though this should represent a DECIMAL, not a DOUBLE!

IMN logo majestic logo threadwatch logo seochat tools logo