Thread: how to compare decimals in c programming

  1. #1
    Registered User
    Join Date
    May 2011

    how to compare decimals in c programming

    hi i am using unix cygwin compiler, courtesy of NUS.
    i know we can use if statements to compare integers but how about decimals(just as they are) ??? Thank you and sorry if this is a petty question.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    You want to use a float type, otherwise it is the same.

    HOWEVER, there is a caveat with comparing floats. Because of the nature of floating point numbers in a computer, they are only exactly equal to decimal values that are an inverse power of two -- 0.5, 0.25, 0.125, 0.0625, and so on. Notice 0.1 is not on the list.

    Try this:

    #include <stdio.h>
    int main() {
            float i;
            for (i=0.0f; i<20; i+=0.1f) {
            return 0;
    It does not do what you would think:


    So much for 0.1! This happens at different points for 32-bit and 64-bit systems.

    Because of that, use a range instead of ==:

    float x;
    if (x >= 10.1999 &&  x <= 10.2001)
    Instead of

    if (x == 10.2)
    Last edited by MK27; 05-15-2011 at 09:49 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to compare, without using compare (homework)
    By Mr.777 in forum C++ Programming
    Replies: 8
    Last Post: 03-07-2011, 02:55 AM
  2. compare with chars && compare with int
    By zcrself in forum C Programming
    Replies: 1
    Last Post: 04-22-2010, 03:19 AM
  3. decimals to hex
    By rajkumarmadhani in forum C Programming
    Replies: 2
    Last Post: 08-08-2007, 11:29 AM
  4. Getting enough decimals
    By Drogin in forum C++ Programming
    Replies: 3
    Last Post: 10-29-2005, 09:37 PM
  5. decimals
    By RyeDunn in forum C++ Programming
    Replies: 13
    Last Post: 07-15-2002, 01:37 AM