问题
I am trying to format some float
s as follows:
1.1500 would be displayed as “$ 1.15”
1.1000 would be displayed as “$ 1.10”
1.0000 would be displayed as “$ 1.00”
1.4710 would be displayed as “$ 1.471”
1.4711 would be displayed as “$ 1.4711”
I tried with
NSString *answer = [NSString stringWithFormat:@"$ %.2f",myvalue];
回答1:
I have figure out this. you can do this as per below implementation.
Please take a look at below demo code...
NSArray * numbers = [[NSArray alloc] initWithObjects:@"1.1500",@"1.1000",@"1.0000",@"1.4710",@"1.4711",nil];
for (int i=0; i<[numbers count]; i++) {
NSArray * floatingPoint = [[numbers objectAtIndex:i] componentsSeparatedByString:@"."];
NSString * lastObject = [[floatingPoint lastObject] stringByReplacingOccurrencesOfString:@"0" withString:@""];
if ([lastObject length] < 2) {
NSLog(@"%@",[NSString stringWithFormat:@"$ %.2f",[[numbers objectAtIndex:i] floatValue]]);
} else {
NSLog(@"%@",[NSString stringWithFormat:@"$ %g",[[numbers objectAtIndex:i] floatValue]]);
}
}
Thanks,
MinuMaster
回答2:
This is exactly what NSNumberFormatters are for:
float onefifteen = 1.1500; // displayed as “$ 1.15”
float oneten = 1.1000; // displayed as “$ 1.10”
float one = 1.0000; // displayed as “$ 1.00”
float onefortyseventen = 1.4710; // displayed as “$ 1.471”
float onefortyseveneleven = 1.4711; // displayed as “$ 1.4711”
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setUsesSignificantDigits:YES];
// The whole number counts as the first "significant digit"
[formatter setMinimumSignificantDigits:3];
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onefifteen]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:oneten]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:one]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onefortyseventen]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onefortyseveneleven]]);
2011-12-15 19:36:52.185 SignificantCents[49282:903] $1.15
2011-12-15 19:36:52.190 SignificantCents[49282:903] $1.10
2011-12-15 19:36:52.190 SignificantCents[49282:903] $1.00
2011-12-15 19:36:52.191 SignificantCents[49282:903] $1.471
2011-12-15 19:36:52.192 SignificantCents[49282:903] $1.4711
回答3:
try this :
NSString *answer = [NSString stringWithFormat:@"%.02f", myvalue];
回答4:
Read the docs on format specifiers.
来源:https://stackoverflow.com/questions/8518603/truncate-extra-zeroes-when-formatting-a-float-into-an-nsstring