# How to get the decimal part of a number...

• 06-11-2006
Caldus
How to get the decimal part of a number...
Say for example I have a double value like 237.3455. For some reason, I can't figure out how to just get the .3455 part of that number. I tried modding it by 1 (as this works for the Google calculator), but C++ doesn't like the left operand being a double for the modulus operator. Any other methods?
• 06-11-2006
Tonto
I'd say like

Code:

`thatNumber - (int) thatNumber`
• 06-11-2006
Dave_Sinkula
Code:

```#include <stdio.h> #include <math.h> int main(void) {     double integer, value = 237.3455, fraction = modf(value, &integer);     printf("value = %g, integer = %g, fraction = %g\n",           value, integer, fraction);     return 0; } /* my output value = 237.345, integer = 237, fraction = 0.3455 */```
• 06-12-2006
henrychan22
double number=237.3455

if(number>=100 && number <=999)
double decimalPart=((number%100)%10)%1

else if
etc
• 06-12-2006
Mario F.
... and if the number is on the trillions you will have a lot of ifing to do there. I don't think so... ;)

modf() is the perfect solution whereas Sinkula's is the most pretty. I would only remove the C style casting in favor of C++ way.
• 06-12-2006
wyvern
here is a good way
try this:

Code:

``` float var1 = 123.456; int tmp = (int)var1; int var2 = var1 - tmp; if ( var2 < 0 ) var2+1;    // cause the decimal part could be like 701 and                   // it will change the  tmp to 124 instead of 123```

PS:
see this is what a real hacker does.... figures out a way of solving a problem that the others never thought off. dont misunderstand with cracker.
• 06-12-2006
whiteflags
On the other hand, Dave's solution is both easily understood and faster than yours. The OP didn't say he wanted a hack solution.
• 06-12-2006
Mario F.
Quote:

// cause the decimal part could be like 701 and
... and an hacker double checks his logic. A cast to int doesn't round. It truncates. Your if statement is unecessary.
• 06-12-2006
Dave_Sinkula
Quote:

Originally Posted by wyvern
see this is what a real hacker does.... figures out a way of solving a problem that the others never thought off.

Try posting something correct that solves the problem before bragging about it.
• 06-12-2006
Mario F.
By the way, just the final nail on the coffin. I'm sure you don't mind, Wyvern. After all an hacker loves to learn new things too... It always produces 0 as the result.
• 06-12-2006
CornedBee
Of course it does. After all, it's just Tonto's method, and then converting the decimal part gained to an int, thus guaranteeing 0 as the result. (Oh, and "var2+1" does nothing on its own. You need to assign the result.)
• 06-12-2006
Tonto
AN EXPLOSION DOESNT HAPPEN CUZ GOD WANTS, IT HAPPENS WHEN A SOMETHING "EXPLODES
• 06-12-2006
Dante Shamest