Я прочитал this и that. Я хочу, чтобы это точно:Ограничьте число с двумя до двух знаков после запятой без конечных нулей
1,4324 => "1,43"
9,4000 => "9,4"
43,000 => "43"9,4 => "9,40" (неправильно)
43,000 = > «43,00» (неверно)
В обоих вопросах ответы указаны на NSNumberFormatter
. Так что это должно быть легко достичь, но не для меня.
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 20)];
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setPaddingPosition:NSNumberFormatterPadAfterSuffix];
[doubleValueWithMaxTwoDecimalPlaces setFormatWidth:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.];
//NSNumber *myValue = [NSNumber numberWithDouble:0.1];
myLabel.text = [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue];
[self.view addSubview:myLabel];
[myLabel release];
myLabel = nil;
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
}
Я также пробовал с
NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]];
NSLog(@"%@", resultString);
Так как я могу отформатировать двойные значения с максимум двух знаков после запятой? Если последняя позиция содержит нуль, нулевое значение должно быть опущено.
Решение:
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
Вы хотите округлить? То есть должно быть 1.4363 => "1.43" или "1.44"? –
Я думаю, что это имело бы смысл. – testing
Не забудьте выпустить doubleValueWithMaxTwoDecimalPlaces в конце концов ... – Lukasz