this ve that'u okurum. Bunun tam olarak istiyorum:Sıfırlar olmadan bir iki ila iki ondalık basamağı sınırla
1,4324 => "1.43"
9,4000 => "9.4"
43,000 => "43"9.4 => "9.40" (yanlış)
43,000 = > "43,00" (yanlış)
Her iki soruda da yanıtlar NSNumberFormatter
. Yani başarması kolay olmalı, benim için değil.
- (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;
}
Ben de maksimum iki ondalık basamaklı çift değerlerini biçimlendirmek nasıl Yani
NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]];
NSLog(@"%@", resultString);
ile çalıştı? Son konum sıfır içeriyorsa sıfır kalmamalıdır.
Çözüm:
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
Yuvarlama ister misiniz? Bu 1.4363 => "1.43" veya "1.44" olmalıdır? –
Bunun mantıklı olacağını düşünüyorum. – testing
Tüm bunlardan sonra doubleValueWithMaxTwoDecimalPlaces yayınlamayı unutmayın ... – Lukasz