如果浮点数小于1,如何将浮点数渲染为2个空格

时间:2012-05-16 05:45:04

标签: objective-c ios

iOS中的

我有一个距离选择器:

  0.25 miles
  1.00 miles
  3.00 miles

并呈现为:

cell.textLabel.text=[NSString stringWithFormat: @"%.2f miles", [i floatValue]];

我将如何渲染:

0.25
1 
3

THX

2 个答案:

答案 0 :(得分:2)

你的意思是,如果小于1,还要做点什么吗?

if ([i floatValue]<1) {
   cell.textLabel.text=[NSString stringWithFormat: @"%.2f miles", [i floatValue]];
}
else {
   cell.textLabel.text=[NSString stringWithFormat: @"%.0f miles", [i floatValue]];
}

答案 1 :(得分:2)

尝试使用NSNumberFormatter。一个简短的例子:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
double d1 = 0.25;
double d2 = 1.00;
double d3 = 3.00;
NSLog(@"d1: %@\nd2: %@\nd3: %@", [numberFormatter stringFromNumber:[NSNumber numberWithDouble:d1]], [numberFormatter stringFromNumber:[NSNumber numberWithDouble:d2]], [numberFormatter stringFromNumber:[NSNumber numberWithDouble:d3]]);

输出:

2012-05-16 07:50:17.153 testApp[266:207] d1: 0,25
d2: 1
d3: 3

希望有所帮助