Search code examples
objective-cnsnumber

Nsnumber checking digits after floating point


I am constructing NSNumber object from a float value.NSNumber *start =[NSNumber numberWithFloat:[self obj.value]];

This gives me start value for example

14.85

I want to do couple of things here, firstly I want to extract the digits after decimal point. In this case 85, I want to assign 85 to a temp object. Then i will perform following check on this newly created temp object.

if (temp >=30){
start = 14.30;
}
else start== 14.0 ;

I have an idea with simple float numbers in C I could achieve this as follows

if ((res-(int)res>=30))
        res= (int)res +.30;
        else res = (int)res;

Solution

  • Here you have an example of how you could do it simple:

    NSNumber *start = [NSNumber numberWithFloat:14.85];
    float startFloat = [start floatValue];
    int startInt = [start intValue];
    int decimalPart =  (startFloat - startInt) * 100 ;
    
    if (decimalPart >= 30){
        NSLog(@"------------- decimalPart >= 30");
        NSLog(@"------------- Do something");
    
    }
    else {
        NSLog(@" ------------- decimalPart < 30");
        NSLog(@"------------- Do something");
    }