在这里,我使用NSNumberFormater
将最大小数位数设置为双精度为 2。它似乎工作正常,但是当我尝试从 生成的字符串将其转换回双精度时NSNumberFormater
,正如您在NSLog
输出中看到的那样,任何小数都被删除并替换为尾随零。为什么是这样?
- (double)randomDoubleBetween:(double)smallNumber and:(double)bigNumber {
double diff = bigNumber - smallNumber;
double ranNum = (((double) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
NSNumberFormatter *doubleValueWithMaxDecimalDigits = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxDecimalDigits setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxDecimalDigits setMaximumFractionDigits:2];
NSNumber *num = [NSNumber numberWithDouble:ranNum];
NSString *valueToReturn = [doubleValueWithMaxDecimalDigits stringFromNumber:num];
NSLog(@"String value %@", valueToReturn);
NSLog(@"Double value converted from string %f", [valueToReturn doubleValue]);
return [valueToReturn doubleValue];
}
NSLog 输出:
2013-08-09 02:25:05.031 GG[27947:907] 字符串值 176,19
2013-08-09 02:25:05.035 GG[27947:907] 从字符串 176.000000 转换的双精度值