Click here to Skip to main content
15,614,943 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
For example, I got:

18.75 but I want to separate them into two different variables, 18 and 75?

What I have tried:

I've tried the modf function and converted to an int, but is there an easier way to do it other than this?
Updated 15-Jan-17 21:51pm
Peter_in_2780 15-Jan-17 23:32pm    
Really crude, but effective:
sprintf(tempstring, "%f", inputfloatnumber);
sscanf(tempstring, "%d.%d" &integerpart, &fractionpart);
You can do all sorts of fancy things by decorating the %f format specifier
Bernhard Hiller 16-Jan-17 4:32am    
Reminds me of a bug introduced by genius programmers in the US headquarters of a previous employer: they reasoned that an IP address can be represented by two floating point numbers which get joined by a dot. Worked well in the US. But here in Germany, it failed miserably: 192,168.0,42 is not a correct IP address...
KarstenK 17-Jan-17 10:44am    
modf is easy, it gave two results with one function.

but is there an easier way to do it other than this?
No, As far as I know. Extracting the integral part is simple: just assign the double to an integer variable. However, transforming the decimal part to an integer is less obvious. After all, there should be a reason the modf function exists.
Share this answer
Daniel Pfeffer 19-Jan-17 10:55am    
Extraction of the integer part by assigning the 'double' to an 'int' is not a good idea. What if the integer part overflows an 'int'?

(e.g. the 'double' value is 2^31, and the 'int' is 32-bit twos complement.)
CPallini 19-Jan-17 13:26pm    
Well, of course it is not valid for the general case. However, if you know what you are doing, i.e. you know in advance the operands are bounded, you may safely use it.
Have a look at the modf function
C Language: modf function (Split into Integer and Fractional Parts)[^]

Here is links to references books on C and C++ by the authors of the languages. Note than C is the ancestor of C++, so knowing C is always useful with C++.
The C Programming Language - Wikipedia, the free encyclopedia[^][^][^]

C++ Programing Language[^]

I've tried the modf function and converted to an int, but is there an easier way to do it other than this?
What is your problem with modf ? it does exactly what you want.
Share this answer
Peter_in_2780 16-Jan-17 1:11am    
OP already said he'd used modf
Patrice T 16-Jan-17 1:25am    
ooops. Missed the last sentence.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900