Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
May 6, 1997

Type conversion

Question:
How does one convert a double to an int? Is there a function like floor that actually returns an int?

Answer:
There are many things you can do to convert a float to an int depending upon what results you expect. If you want to use the built-in language conversions, you can simply assign the float to an integer. For example:

float f = 9.99;
int i;

i = int(f); // conversion.. truncates.
This will truncate the value and always return the integral part.

Also, notice that the typecast to int was not really necessary, but I like to write it explicitly to make my intentions well-known. If you want to achieve something with the conversion other than the standard behavior, you will have to use functions from the standard C++ or C library.

Two useful functions are floor and ceil. Both of these return float, but the value can be used as an integer.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date