newbie ques - check double

A

Apple

is there any simple way to check if the value of a double is an integer?
like,

double d;
d = 15.5 => NOT an integer
d = 15.0 => IS an integer

if there's no standard function to do that, can anyone give me a hint on how
to write a right one?

thanks.
 
J

John Harrison

Apple said:
is there any simple way to check if the value of a double is an integer?
like,

double d;
d = 15.5 => NOT an integer
d = 15.0 => IS an integer

if there's no standard function to do that, can anyone give me a hint on how
to write a right one?

if (d == floor(d))
// d is an integer

john
 
D

David Harmon

On Tue, 28 Sep 2004 17:43:34 GMT in comp.lang.c++, "Mike Wahler"
Another alternative is to use 'modf()'.

And there are others. But testing any floating point result for any
exact value typically indicates wrong thinking in the design anyway.
Resist the temptation and save having to fix it in the end!
 
Z

Zian Smith

Apple said:
is there any simple way to check if the value of a double is an integer?
like,

double d;
d = 15.5 => NOT an integer
d = 15.0 => IS an integer

if there's no standard function to do that, can anyone give me a hint on how
to write a right one?

thanks.

Try this:

double d;
bool isInt;

isInt = (int(d)-d) ? false : true;
 
M

Mike Wahler

Zian Smith said:
"Apple" <[email protected]> wrote in message

Try this:

double d;
bool isInt;

isInt = (int(d)-d) ? false : true;

This can lead to possible undefined behavior (e.g. if
the value of 'd' is greater than 'INT_MAX' or less than
'INT_MIN'. Use the library functions, that's what they're
there for.

-Mike
 
M

Mike Wahler

David Harmon said:
On Tue, 28 Sep 2004 17:43:34 GMT in comp.lang.c++, "Mike Wahler"


And there are others. But testing any floating point result for any
exact value

OP is not looking for an 'exact value', but simply whether
a real number has a fractional part. Also note that types
'float' and 'double' can indeed represent integers exactly.
typically indicates wrong thinking in the design anyway.

I don't think it's 'wrong thinking' to try to determine
if a real number has a fractional part (unless of course
it's not really needed by the application being written).

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top