舍入浮动到第一个非零值

时间:2012-04-28 10:12:59

标签: objective-c ios xcode floating-point

伙计们,我有一些很少的花车,我想把它四舍五入到第一个不是零值。 例如:

float toRound = 0.000002125231553;
toRound = //Operations//;

toRound == 0.000002;

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

也许不是最好的方法。但它做你想要的;)

float s = 0.000322333123;
BOOL exit = 0;
NSString *x = [NSString stringWithFormat:@"%f", s];
for (int i = 0; i <= [x length]; i++) {
NSString *t = [x substringToIndex:i];

if ([t floatValue] == 0 || exit == 1) {
    ;;
}
else {
    exit = 1;
    s = [t floatValue];       
}
}

NSLog(@"round: %f", s);

记录:舍入:0.0003