# 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 on other sites

Money is not an int.

##### Share on other sites

this is due to floating point conversion errors.

see this link on how to do this math using binary coded decimal numbers, i.e. like a hand-held calculator does - https://www.php.net/manual/en/book.bc.php

##### Share on other sites
```\$price = 278.53;
\$cents = \$price * 100;
\$end_result = \$cents ;          // without the (int) gives 27853```

##### Share on other sites

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

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

##### 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 on other sites

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

##### 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 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.

## Join the conversation

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

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

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

×

×

• #### Activity

• Chat
×
• Create New...