I have a number for example: 2.4444444
. I need to get first digit after the dot -- in my case it's 4
. How to implement it?
Asked
Active
Viewed 4,801 times
2

undur_gongor
- 15,657
- 5
- 63
- 75

LightNight
- 1,616
- 6
- 30
- 59
-
1convert it as string and separate the string after '.'Now get the first indexvale from string – EXC_BAD_ACCESS Nov 17 '11 at 09:06
4 Answers
6
How about
( (int)(floor( fabs( num ) * 10 ) ) ) % 10

Kiril Kirov
- 37,467
- 22
- 115
- 187
-
You're welcome :) You can even make a constant, let's say `int nNumberAfterDecimalPoint = 1;` and instead of hard-coding `10` (as in my solution), you can make it `( (int)(floor( fabs( num ) * ( 10 * nNumberAfterDecimalPoint ) ) ) % 10`. This will make it a little more flexible and you'll be able to get not only the first digit after the decimal point, but whichever you like only by changing the constant :) Anyway. – Kiril Kirov Nov 17 '11 at 10:33
4
Chech these out! Tried it for you hope it helps
#include<stdio.h>
int main()
{
int b;
float a;
a=2.4444; 'load some value
b=(int)a; 'typecast it into integer you get 2 into b variable
a=a-b; ' subtract b from a and you will get decimal point value 0.4444
a=a*10; ' multiplying with 10 gives 4.444
b=(int)a; ' now apply the same logic again
printf("%d",b); 'outputs 4
}
Update written these function using these link
0
-
@Wevah is right, you need both - `floor` and `(f)abs`. `(int)` will round the number (for example - 5.6 would become 6 ) – Kiril Kirov Nov 17 '11 at 10:34
-
3Typecasting to int doesn't round numbers, it truncates them. At least that's how it's done in almost any computer language I'm aware of. I doubt Object-C is an exception. – zmbq Nov 17 '11 at 10:46