Enlil
Enlil

Reputation: 1047

How to know if a float got a decimals

I'm building a simple calculator for a classroom, this is the code to show the result:

- (void)doTheMathForPlus:(float)val {
    float conto = self.contBox + val;
    self.myDisplay.text = [NSString stringWithFormat:@"%.02f", conto];
}

I need to know if "conto" have decimals (to change the format of the string in a if statement)

how to do it?

thanks

Upvotes: 5

Views: 3631

Answers (3)

3CC
3CC

Reputation: 502

you'd better wrap that with #define and put this line in your .pch file

#define HAS_DECIMALS(x) (x!=(int)x)

than use anywhere in the code:

if (HAS_DECIMALS(conto)) {
    //number has decimals 
} else {
    //number does not have decimals
}

Upvotes: 3

dredful
dredful

Reputation: 4388

if (conto == (int)conto) {


}

Hope this helps.

Upvotes: 9

Vov4yk
Vov4yk

Reputation: 1080

Yes, dredful is right with his answer. And, You also can use different functions like floor, ceil, round. In You case better "floor(conto)".

But, you can't do like Kyr Dunenkoff suggested. becouse, all operands for"%" should be integer, but not float as "conto".

Upvotes: 1

Related Questions