我正在尝试格式化一些float
,如下所示:
1.1500将显示为“$ 1.15”
1.1000将显示为“$ 1.10”
1.0000将显示为“$ 1.00”
1.4710将显示为“$ 1.471”
1.4711将显示为“$ 1.4711”
我试过
NSString *answer = [NSString stringWithFormat:@"$ %.2f",myvalue];
答案 0 :(得分:7)
这正是NSNumberFormatter
s的用途:
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重要事项[49282:903] $ 1.15
2011-12-15 19:36:52.190重要事项[49282:903] $ 1.10
2011-12-15 19:36:52.190重要事项[49282:903] $ 1.00
2011-12-15 19:36:52.191重要事项[49282:903] $ 1.471
2011-12-15 19:36:52.192重要事项[49282:903] $ 1.4711
答案 1 :(得分:1)
试试这个:
NSString *answer = [NSString stringWithFormat:@"%.02f", myvalue];
答案 2 :(得分:0)
我已经弄明白了。您可以按照以下实施方式执行此操作。
请看下面的演示代码......
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]]);
}
}
谢谢,
MinuMaster
答案 3 :(得分:-2)