Is there an easy way to round a float with a single digit number in lens c?

Yes. You're right. Of course, this is a recurring question. Before asking your question, please continue reading below.

I want to round the float value, which

56.6748939 to 56.7
56.45678 to 56.5
56.234589 to 56.2

In fact, it can be any number of decimal prefixes. But I want to round it to the nearest value. (If it is greater than or equal to 5, then round, and if not, then round down).

I can do this with the code below.

float value = 56.68899
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];

NSString *roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber *roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];

The above code looks like a lengthy process. I have a few rooms left. Thus, this process is difficult to convert the float value to NSNumber and NSString and NSNumber and float.

Is there any other easy way to achieve what I asked?

. roundUp. , roundDown, ?

0
6

10, , 10?

+6

CGFloat float1 = 56.6748939f;
CGFloat float2 = 56.45678f;

NSLog(@"%.1f %.1f",float1,float2);

56,7 56,5

:

float value = 56.6748939f;
NSString *floatString = [NSString stringWithFormat:@"%.1f",floatValue];
float roundedValue = [floatString floatValue];
+3

[dictionaryTemp setObject:[NSString stringWithFormat:@"%.1f",averageRatingOfAllOrders] forKey:@"AvgRating"];

%. 1f 2.1 .

+2
    NSString* strr=[NSString stringWithFormat: @"%.1f", 3.666666];
    NSLog(@"output is:  %@",strr);

: 3.7

    float fCost = [strr floatValue];
+1

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setMinimumFractionDigits:0];

CGFloat firstnumber = 56.6748939;
NSString *result1 = [formatter stringFromNumber:[NSNumber numberWithFloat:firstnumber]];

NSLog(@"RESULT #1: %@",result1);

CGFloat secondnumber = 56.45678;
NSString *result2 = [formatter stringFromNumber:[NSNumber numberWithFloat:secondnumber]];

NSLog(@"RESULT #2: %@",result2);

CGFloat thirdnumber = 56.234589;
NSString *result3 = [formatter stringFromNumber:[NSNumber numberWithFloat:thirdnumber]];

NSLog(@"RESULT #2: %@",result3);
0

You do not want to swim, because it gives you only six or seven digits. You also don't want CGFloat because it only gives you six or seven digits, with the exception of iPad Air or iPhone 5s. You want to use double.

Rounding to one digit is very simple:

double x = 56.6748939;
double rounded = round (10 * x) / 10; 
0
source

All Articles