Rounded of a float with a decimal

Do someone know if there is a method in order to round a float two numbers after the comme.

Examples :

10.28000 -> 10.3
13.97000 -> 14.0
5.41000 -> 5.4

Thanks a lot !

Regards, Sébastien ;)

Upvotes: 0

Views: 188

Answers (6)

maz
maz

Reputation: 8336

The pure Cocoa way with NSRoundPlain behaviour:

- (NSDecimalNumber *)decimalNumberForFloat:(float)f_

{

NSNumber *number                           = [NSNumber numberWithFloat:f_];
NSDecimal decimal                          = [number decimalValue];
NSDecimalNumber *originalDecimalNumber     = [NSDecimalNumber decimalNumberWithDecimal:decimal];
NSDecimalNumberHandler *roundingBehavior   = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
                                              scale:0
                                              raiseOnExactness:NO
                                              raiseOnOverflow:NO
                                              raiseOnUnderflow:NO
                                              raiseOnDivideByZero:NO];

return [originalDecimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];

}

since NSDecimalNumber is a subclass of NSNumber, to obtain the primitive float call -[NSDecimalNumber floatValue]

Upvotes: 1

Tutankhamen
Tutankhamen

Reputation: 3562

float fval = 1.54f;
float nfval = ceilf(fval * 10.0f + 0.5f)/10.0f;

Upvotes: 0

James Paolantonio
James Paolantonio

Reputation: 2194

Use NSNumberFormatter to create a string with the specified faction digits.

float num = 10.28000;

formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];

NSNumber *value = [NSNumber numberWithFloat:num];
NSString *newNumString = [formatter stringFromNumber:value];

Upvotes: 1

Mahmoud Fayez
Mahmoud Fayez

Reputation: 3459

Try this out:

float myFloat = 10.4246f;
myFloat = ((int) ((myFloat * 100) + 5)) / 100.0f;

Upvotes: 0

Ismael
Ismael

Reputation: 3937

you could also try

float num = 10.28000
float result = (roundf(num * 10.0))/10.0;

(multiply by 10, then round, then divide by 10 again) don't forget the .0 so that the division is by a float and not by an integer, which will round it again

Upvotes: 1

Cyrille
Cyrille

Reputation: 25144

Try this:

float aFloatValue = 3.1415926;
NSString *formatted = [NSString stringWithFormat:@"%01.1f", aFloatValue];
NSLog(@"Formatted: %@", formatted);

Think of it as a good old sprintf.

Upvotes: 1

Related Questions