The problem with going from a double to an int is that the final digit can
be cut off because the double is inexact. But the double will be close.
All you need to do is add 0.5 to the value before doing the conversion to
an int. The "extra" 0.5 will make a value like 4.999999999 get converted
to 5 instead of 4. Unless your original numbers are off by a large amount
(close to 0.5) this won't introdcue any error.
intVal = (int)(dbleVal * 100 + 0.5);
Sr. Software Engineer
Carl Zeiss SMT Inc.
ALIS Business Unit
1 Corporation Way
Peabody, MA 01960 USA
tgriffin@smt.... (978) 826-1569
Re: [ADVANCED-DOTNET] Converting doubles into integers without rounding
Personally, I've never used it before, but I see in framework 2.0 there is
the option of:
(int) Double.Truncate(objMyObject.Amount * 100);
From: Discussion of advanced .NET topics.
[mailto:ADVANCED-DOTNET@DISC...] On Behalf Of Eddie Lascu
Sent: 25 August 2008 06:28 PM
To: ADVANCED-DOTNET@DISC... Subject: [ADVANCED-DOTNET] Converting doubles into integers without
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
error that is introduced and the integer obtained is off by a cent (plus
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?
This message is intended for a particular addressee only and may contain business or company secrets. If you have received this email in error, please contact the sender and delete the message immediately. Any use of this email, including saving, publishing, copying, replication or forwarding of the message or the contents is not permitted.