473,568 Members | 2,898 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rounding error casting from float to int

Hi all, I just discovered a rounding error that occurs in C#. I'm sure
this is an old issue, but it is new to me and resulted in a fair amount
of time trying to track down the issue.

Basically put the following code into your C# app:
float testFloat2 = (int) (4.2f * (float)100);
Console.Out.Wri teLine("1: "+testFloat 2);

and the result will be 419

If I use Convert.ToInt32 I can get around this problem - but it seems
that both should do the same thing, shouldn't they?

Novice

Mar 15 '06 #1
12 13630
Actually, it's not a C# problem at all. Floating point numbers are
rarely exact. So 4.2 is actually something like 4.199999999. Thus the result
you see.
Bob
<6t**@qlink.que ensu.ca> wrote in message
news:11******** *************@u 72g2000cwu.goog legroups.com...
Hi all, I just discovered a rounding error that occurs in C#. I'm sure
this is an old issue, but it is new to me and resulted in a fair amount
of time trying to track down the issue.

Basically put the following code into your C# app:
float testFloat2 = (int) (4.2f * (float)100);
Console.Out.Wri teLine("1: "+testFloat 2);

and the result will be 419

If I use Convert.ToInt32 I can get around this problem - but it seems
that both should do the same thing, shouldn't they?

Novice

Mar 15 '06 #2

6t**@qlink.quee nsu.ca wrote:
Hi all, I just discovered a rounding error that occurs in C#. I'm sure
this is an old issue, but it is new to me and resulted in a fair amount
of time trying to track down the issue.

Basically put the following code into your C# app:
float testFloat2 = (int) (4.2f * (float)100);
Console.Out.Wri teLine("1: "+testFloat 2);

and the result will be 419

If I use Convert.ToInt32 I can get around this problem - but it seems
that both should do the same thing, shouldn't they?

Novice


http://www.math.grin.edu/~stone/cour...EEE-reals.html

Mar 15 '06 #3
No offense to the posters (Bob and KBuser), but you haven't really
answered my question. Perhaps I could have phrased it a little better.
I was more interested in why I get a different result from the two
different methods specific to .NET. I'm sure I would get the result if
I wrote equivalent VB.NET - but I happen to program in C#.

Perhaps, I wasn't being clear enough in my original post, if I use
Convert.ToInt32 then I get 420, not 419. So obviously the Convert
method is doing something to make the result more accurate.

Anyway, if anyone knows why I get a different result please feel free
to post it.

Thanks,
Novice

Mar 15 '06 #4
vj
Really not sure why you are type casting to (int) and then storing in a
float variable.. Can I know why?

VJ

<6t**@qlink.que ensu.ca> wrote in message
news:11******** *************@u 72g2000cwu.goog legroups.com...
Hi all, I just discovered a rounding error that occurs in C#. I'm sure
this is an old issue, but it is new to me and resulted in a fair amount
of time trying to track down the issue.

Basically put the following code into your C# app:
float testFloat2 = (int) (4.2f * (float)100);
Console.Out.Wri teLine("1: "+testFloat 2);

and the result will be 419

If I use Convert.ToInt32 I can get around this problem - but it seems
that both should do the same thing, shouldn't they?

Novice

Mar 15 '06 #5
No reason - you get the same behavior regardless whether the variable
being assigned to is of type float or int.

Novice

Mar 15 '06 #6
> If I use Convert.ToInt32 I can get around this problem - but it seems
that both should do the same thing, shouldn't they?


Nope. (int) truncates whereas Convert.ToInt32 rounds

Cheers
Doug Forster
Mar 15 '06 #7
<6t**@qlink.que ensu.ca> wrote:
No offense to the posters (Bob and KBuser), but you haven't really
answered my question.
Well, they answered why you got the answer 419. You're multiplying
4.1999998092651 3671875 by 100. There's no rounding *error* - there's
just a different method of rounding for casts than for Convert.ToInt32 .

<snip>
Perhaps, I wasn't being clear enough in my original post, if I use
Convert.ToInt32 then I get 420, not 419. So obviously the Convert
method is doing something to make the result more accurate.


Well, it's choosing a different method of rounding.

From the docs for Convert.ToInt32 :

<quote>
value rounded to the nearest 32-bit signed integer. If value is halfway
between two whole numbers, the even number is returned; that is, 4.5 is
converted to 4, and 5.5 is converted to 6.
</quote>

From the C# 1.1 language spec, (ECMA numbering) section 13.2.1:

<quote>
For a conversion from float or double to an integral type, the
processing depends on the overflow-checking context (§14.5.12) in which
the conversion takes place:

....

In an unchecked context, the conversion always succeeds, and proceeds
as follows:

If the value of the source operand is within the range of the
destination type, then it is rounded towards zero to the nearest
integral value of the destination type, and this integral value is the
result of the conversion.
</quote>

So, one is rounding to nearest, the other is rounding towards zero.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 15 '06 #8
Great - this is what I was looking for.

Thanks very much,
Novice

Mar 15 '06 #9
Doug summarizes it rather well. The one truncates and the other
rounds. In other words, you could get the int cast (int) to result in
a cast to zero if the number was something like this:
4.2000000000000 0000009
it simply ignores the least significant bits. Whereas the
Convert.ToInt32 would get the same result, because rounding the above
number still results in 420.

So because of the inaccuracies of the representation of numbers - it
seems like the Convert method would yield the expected results in all
cases. Or can someone think of some way in which the Convert method
would yield the unexpected and the int cast would yield the expected?

Thanks,
Novice

Mar 15 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
12993
by: Quinn Kirsch | last post by:
Hi all, the following c# example baffles me. my understanding of the managed code of visual .net is that all casts like this would be safe, but this example seems to contradict this notion. if you look at the debugger info, the double dou is half filled w/ garbage bits, instead of those bits being zeroed out appropriately. using System;...
11
6187
by: ravi.sathyam | last post by:
Hi, so basically I define a struct as follows: struct speechSegment { float coeff_Array; float period; float energy; }; struct speechSegment segment = { /*I fill this struct with info */};
21
2667
by: Karl O. Pinc | last post by:
FYI, It'd be nice if the error message from a REFERENCES constraint mentioned the column name into which the bad data was attempted to be inserted. In PostgreSQL 7.3: sandbox=> insert into foo (id, b) values (3, 2); ERROR: b_is_fkey referential integrity violation - key referenced from
29
3152
by: Marco | last post by:
Hello, I have : float f = 36.09999999; When I do : char cf; sprintf(cf,"%0.03lf", f); I get : 36.100
13
6166
by: Shirsoft | last post by:
I have a 32 bit intel and 64 bit AMD machine. There is a rounding error in the 8th digit. Unfortunately because of the algorithm we use, the errors percolate into higher digits. C++ code is ------------------ b += (float)(mode *val); On 32 bit(intel , vs 2003, C++), some watch variables are
17
2204
by: sophia.agnes | last post by:
Hi , I was going through peter van der linden's book Expert C programming, in this book there is a section named "How and why to cast" the author then says as follows (float) 3 - it's a type conversion and the actual bits change. if you say (float) 3.0 it is a type disambiguation,and the compiler can plant the correct bits in the first...
206
13169
by: md | last post by:
Hi Does any body know, how to round a double value with a specific number of digits after the decimal points? A function like this: RoundMyDouble (double &value, short numberOfPrecisions) It then updates the value with numberOfPrecisions after the decimal
20
4970
by: jacob navia | last post by:
Hi "How can I round a number to x decimal places" ? This question keeps appearing. I would propose the following solution #include <float.h> #include <math.h>
0
7916
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7660
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6275
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5498
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
932
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.