NSNumberFormatter numberFromString 问题
NSNumberFormatter numberFromString issue
我需要从 UITextfield 中取出一个字符串并将其格式化为以下格式:
4.99999 -> 4.999
4.12 -> 4.12
.89 -> 0.89
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:3];
[numberFormatter setPositiveFormat:@"##0.###"];
DLog(@"formatted number %@",[numberFormatter numberFromString:string]);
问题是,当我在文本字段中键入 0.999978 并且格式化的数字是 0.999978(这是不正确的)时,它应该是 0.999
试一试:
NSNumber *aNum = [NSNumber numberWithDouble:[string doubleValue]];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setPositiveFormat:@"##0.###"];
[numberFormatter setRoundingMode:NSNumberFormatterRoundFloor];
DLog(@"formatted string %@",[numberFormatter stringFromNumber:aNum]);
我需要从 UITextfield 中取出一个字符串并将其格式化为以下格式:
4.99999 -> 4.999
4.12 -> 4.12
.89 -> 0.89
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:3];
[numberFormatter setPositiveFormat:@"##0.###"];
DLog(@"formatted number %@",[numberFormatter numberFromString:string]);
问题是,当我在文本字段中键入 0.999978 并且格式化的数字是 0.999978(这是不正确的)时,它应该是 0.999
试一试:
NSNumber *aNum = [NSNumber numberWithDouble:[string doubleValue]];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setPositiveFormat:@"##0.###"];
[numberFormatter setRoundingMode:NSNumberFormatterRoundFloor];
DLog(@"formatted string %@",[numberFormatter stringFromNumber:aNum]);