15,614,943 members
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?
Posted
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.

## Solution 2

Quote:
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.

v2
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.

## Solution 1

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[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]

C++ Programing Language[^]

[Update]
Quote:
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.

v3
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)

Top Experts
Last 24hrsThis month
 OriginalGriff 130 raddevus 75 CHill60 35 Rick York 30 Richard MacCutchan 30
 OriginalGriff 2,996 Richard MacCutchan 1,266 Graeme_Grant 965 Dave Kreskowiak 649 CHill60 360

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