如何从目标c中的浮点数获取小数点后的数字
答案 0 :(得分:1)
好的,这是C风格,但我想这个过程是一样的。
int decimals = (number -((int)number) );
while( decimals > 0.0 )
{
reportNextNumber( (int)(decimals*10) );
decimals = (number -((int)number) );
}
答案 1 :(得分:0)
此代码有效
CGFloat x = 2.43;
// CGFloat x = 3.145;
// CGFloat x = 2.0003;
// CGFloat x = 1.0;
// CGFloat x = 3.1415926535;
NSLog(@"%f -> %@", x, @([self numberOfFractionDigits:x]));
- (NSString *)numberOfFractionDigits:(CGFloat)number {
CGFloat fractionalPart = number - (NSInteger)number;
NSMutableString *r = [NSMutableString stringWithString:@""];
while (fractionalPart) {
[r appendFormat:@"%@", @((NSUInteger)(fractionalPart * 10 + .5))];
number *= 10;
fractionalPart = number - (NSInteger)number;
}
return r;
}
输出:
2.430000 - > 43
3.145000 - > 145
2.000300 - > 0003
1.000000 - >
3.141593 - > 1415926535 // for x = 3.1415926535;