Franco Altuna
Franco Altuna

Reputation: 328

Not getting any decimals Objective-C

Im getting pretty desperate with this. It should be easy but somehow Im doing something wrong.

I have this code to display the result of a well know physics equation, however I don't seem to get the decimals on the answer. If the answer is 2.5 i get 2.00 if it is 0.2 I get 0.00. Can someone picture out why?

On the .h file:

@interface MyController : UIViewController {

    float result;   
}

@property (strong, nonatomic) IBOutlet UILabel *VariableResult;

On the .m file:

    if ([VariableSelected.text isEqual: @"Position"]) {
    result = [VelocityVariable.text intValue] * [AccelerationVariable.text intValue] *   [TimeVariable.text intValue];
    VariableResult.text = [NSString stringWithFormat:@"%2f", result];
}

Upvotes: 0

Views: 37

Answers (2)

Indrajeet
Indrajeet

Reputation: 5666

You are multiplying int value that's why you are getting this result, replace intValue with floatValue as shown below

if ([VariableSelected.text isEqual: @"Position"]) 
{
    result = [VelocityVariable.text floatValue] * [AccelerationVariable.text floatValue] * [TimeVariable.text floatValue];
    VariableResult.text = [NSString stringWithFormat:@"%2f", result];
}

Upvotes: 1

Claus Jørgensen
Claus Jørgensen

Reputation: 26344

Integer multiplied by integer, remains an Integer. You should get the floatValue instead of the intValue, ie.

result = [VelocityVariable.text floatValue] 
       * [AccelerationVariable.text floatValue] 
       * [TimeVariable.text floatValue];

You may also consider using a NSNumberFormatter

NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
nf.positiveFormat = @"0.##";
VariableResult.text = [nf stringFromNumber:[NSNumber numberWithFloat:result]];

Upvotes: 1

Related Questions