2

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?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
LightNight
  • 1,616
  • 6
  • 30
  • 59

4 Answers4

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

Extract decimal part from a floating point number in C

Community
  • 1
  • 1
niko
  • 9,285
  • 27
  • 84
  • 131
1

it could be as simple as

num*10%10
bigOmega ツ
  • 371
  • 3
  • 13
0
(int)(num * 10) - ((int)num) * 10
Luke
  • 11,426
  • 43
  • 60
  • 69
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • @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
  • 3
    Typecasting 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