Ho letto this e that. Voglio che questo esattamente:Limita un doppio a due decimali senza zero finale
1,4324 => "1.43"
9,4000 => "9.4"
43.000 => "43"9.4 => "9.40" (sbagliato)
43.000 = > "43.00" (errato)
In entrambe le domande le risposte indicano NSNumberFormatter
. Quindi dovrebbe essere facile da raggiungere, ma non per me.
- (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;
}
Ho anche provato con
NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]];
NSLog(@"%@", resultString);
Così come posso formattare valori doppi con un massimo di due cifre decimali? Se l'ultima posizione contiene uno zero, lo zero deve essere omesso.
Soluzione:
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;
Vuoi arrotondare? Vale a dire 1.4363 => "1.43" o "1.44"? –
Penso che avrebbe senso. – testing
Non dimenticare di rilasciare doubleValueWithMaxTwoDecimalPlaces dopo tutto ... – Lukasz