Testing for a decimal point

This is a discussion on Testing for a decimal point within the C++ Programming forums, part of the General Programming Boards category; Is there anyway to test whether a 'double' contains a decimal point?...

  1. #1
    Refugee face_master's Avatar
    Join Date
    Aug 2001
    Posts
    2,052

    Testing for a decimal point

    Is there anyway to test whether a 'double' contains a decimal point?

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    You misunderstand how floating point numbers are stored. A double is a floating point number, which itself means that the number is stored in such a manner that the decimal point is accounted for even when there are nothing but 0s to the right of it.

    So, in a totally useless snippet of code..
    Code:
    bool doesDoubleContainDecimalPoint(double d) {
       return true;
    }
    However, you probably meant "How can I check if a double is an integer?" Well.. in that case..

    Code:
    #include <cmath>
    #include <iostream>
    
    bool isInteger(double d) {
                // check floor docs at
                // http://www.cplusplus.com/ref/cmath/floor.html
    	return d == floor(d);
    }
    
    void test(double d) {
    	std::cout << d << " is ";
    	if (!isInteger(d)) std::cout << "not ";
    	std::cout << "an integer" << std::endl;
    }
    
    int main() {
    	test(3.0);
    	test(2);
    	test(3.14124);
    	test(sqrt(1000.0*1000.0));
    	return 0;
    }
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Classes & Collections
    By Max_Payne in forum C++ Programming
    Replies: 7
    Last Post: 12-11-2007, 12:06 PM
  2. floating point binary program, need help
    By ph34r me in forum C Programming
    Replies: 4
    Last Post: 11-10-2004, 06:10 AM
  3. decimal point allignment
    By Max in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2002, 10:27 PM
  4. about testing a program
    By Abdi in forum C Programming
    Replies: 1
    Last Post: 06-09-2002, 12:51 AM
  5. decimal to binary, decimal to hexadecimal and vice versa
    By Unregistered in forum C++ Programming
    Replies: 9
    Last Post: 12-08-2001, 10:07 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21