From: buers AT gmx DOT de (Dieter Buerssner) Newsgroups: comp.os.msdos.djgpp Subject: Re: Rounding doubles to ints Date: 1 Jun 2000 15:37:29 GMT Lines: 38 Message-ID: <8h67e5.3vs4im1.0@buerssner-17104.user.cis.dfn.de> References: <39363d0a$0$8416$7f31c96c AT news01 DOT syd DOT optusnet DOT com DOT au> NNTP-Posting-Host: pec-142-121.tnt9.s2.uunet.de (149.225.142.121) Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Trace: fu-berlin.de 959873849 2510753 149.225.142.121 (16 [17104]) X-Posting-Agent: Hamster/1.3.13.0 User-Agent: Xnews/03.02.04 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Jason wrote: >Just a quick question - is it standard practice for a c/c++ compiler (such >as DJGPP) to round up-always, down-always or to the nearest-integer when >casting a double to an int? The casting to int will truncate the decimal palces. So int i; i = 1.9; /* i = 1 */ i = -1.9; /* i = -1 */ >If there is no standard for rounding with regard to casting doubles to >ints, would it be best to use floor(), ceil() and round() just in case >(for cross-compiler compatibility)? AFAIK, DJGPP does not support the C99 function round(). So, depending on how you exactly define your rounding problem, you have the possibility of casting to an int, perhaps something like (int)(x + 0.5) for positive x. When the range of int is not enough, or you need the result as a floating point number, you can use floor(x + 0.5). All of this gives you biased rounding, meaning the x.5 always rounds up. Implementing unbiased rounding (always round to even for .5 cases: 0.5 -> 0, 1.5 -> 2, 2.5 -> 2, 3.5 -> 4 ...) in portable C is a little bit more work. If you need this, and are interested in GCC and x86 only, a line of inline assembler might be the easiest. /* untested */ double my_round(double x) { double rounded; /* assume, nobody played with the FPU rounding flags */ __asm__ ("frndint" : "=t" (rounded) : "0" (x)); return rounded; } -- Regards, Dieter Buerssner