Welcome to the wild and wooly world of floating point arithmetic. If you
know that there are always going to be a fixed number of decimal places,
you're often better off storing the value as an integer and adding scaling
logic where needed. This is because the values that can be stored
accurately as floating point numbers are only those whose mantissa can
accurately be expressed as a sum of powers of two. These values include
0.25 (which equals 2^-2) but does not include 0.26.
In general, rounding a decimal to an integer is equivalent to adding 0.5 and
then truncating. In your case, this would mean
uint nIntAmount = (uint)((objMyObject.Amount * 100) + 0.5);
In practice, if your domain really does include only values with "two
decimal places" then it's sufficient to add only a token amount before
truncating. However, the code is more readable and no slower by doing the
complete rounding operation.
> Hello everyone,
> I have some objects that contain an amount field that is declared as
> Since it contains amounts, it always has only two decimal digits that are
> significant. During the process I need to convert that double into an
> integer by removing the decimal point. For example, $78.59 should be
> converted to integer 7859 and $101.53 to 10153. in my code I have
> uint nIntAmount = (uint)(objMyObject.Amount * 100);
> The problem I am facing is that sometimes, very rarely, there is a rounding
> error that is introduced and the integer obtained is off by a cent (plus or
> minus). For example, this is a line that was traced in my log file:
> "Updating the batch with $137.89 as the amount in the transaction. This
> amount was converted to 13788."
> Can either of you suggest a different way to convert the amounts in
> without this nagging rounding error?
> Any help will be appreciated,
> This list is hosted by DevelopMentor(R) http://www.develop.com >
> View archives and manage your subscription(s) at
> http://discuss.develop.com >