Jump to content
fastsol

Help with Integer precision

Recommended Posts

So I am trying to take a string value of dollars (posted from a form) and times it by 100 to get the cents Integer value of the dollars.  For some reason if I do this with something like 278.53  I end up with 27852.  Same concept for 278.59 ends up as 27858.  I don't understand why or how to make it work.  I've tried many things and nothing has made it work.

$price = '278.53'; // posted from the form
$cents = $price * 100; // converting to cents.
end_result = (int)$cents // This will end up being 27852 not 27853.

 

Share this post


Link to post
Share on other sites
$price = 278.53; 
$cents = $price * 100; 
$end_result = $cents ;          // without the (int) gives 27853

 

Share this post


Link to post
Share on other sites

(int) will truncate the number. The actual value is something like 27852.99999999997.

Spoiler for most floating-point problems: round().

  • Like 1

Share this post


Link to post
Share on other sites
10 hours ago, requinix said:

(int) will truncate the number. The actual value is something like 27852.99999999997.

Spoiler for most floating-point problems: round().

round was the one thing I didn't try, Thank you!

This gives the correct result.

$price = '278.53';
$cents = $price * 100;
$end_result = (int)round($cents); // Gives me 27853 as expected.  also works for 278.59 

I knew the issue was a precision thing, I just couldn't find the right combination of functions to make it work.  In the end it was so simple (as I figured it would be).

Share this post


Link to post
Share on other sites
6 hours ago, ginerjm said:

Couldn't you just use the str_replace to remove the dot?

Please no. It is a number. Treat it like a number.

Share this post


Link to post
Share on other sites

Actually the OP began this topic by stating that he was working on a 'string' value (from a form).  If he is willing to move forward with that and is comfortable that the users will input a valid currency amount, my suggestion made sense.  Afterall, it doesn't appear to be a mathematical situation here, simply a formatting change.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.