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 ;)
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 ;)
具有 NSRoundPlain 行为的纯 Cocoa 方式:
- (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];
}
由于 NSDecimalNumber 是 NSNumber 的子类,因此要获取原始浮点调用 -[NSDecimalNumber floatValue]
你也可以试试
float num = 10.28000
float result = (roundf(num * 10.0))/10.0;
(乘以 10,然后舍入,然后再除以 10)不要忘记 .0 以便除以浮点数而不是整数,这将再次舍入
使用 NSNumberFormatter 创建具有指定派系数字的字符串。
float num = 10.28000;
formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
NSNumber *value = [NSNumber numberWithFloat:num];
NSString *newNumString = [formatter stringFromNumber:value];
尝试这个:
float aFloatValue = 3.1415926;
NSString *formatted = [NSString stringWithFormat:@"%01.1f", aFloatValue];
NSLog(@"Formatted: %@", formatted);
认为它是一个很好的旧sprintf
。
试试这个:
float myFloat = 10.4246f;
myFloat = ((int) ((myFloat * 100) + 5)) / 100.0f;
float fval = 1.54f;
float nfval = ceilf(fval * 10.0f + 0.5f)/10.0f;