Jump to content

Help with Integer precision


fastsol

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.

 

Link to comment
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).

Link to comment
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.