iphone - 将 double 限制为两位小数,不带尾随零

标签 iphone objective-c cocoa-touch decimal nsnumberformatter

我读过 thisthat .我正是想要这个:

1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"

9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)

这两个问题的答案都指向NSNumberFormatter。所以它应该很容易实现,但对我来说不是。

- (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.01234];
    //NSNumber *myValue = [NSNumber numberWithDouble:0.1];

    myLabel.text = [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue];

    [self.view addSubview:myLabel];
    [myLabel release];
    myLabel = nil;
    [doubleValueWithMaxTwoDecimalPlaces release];
    doubleValueWithMaxTwoDecimalPlaces = nil;
}

我也试过了

NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]];
NSLog(@"%@", resultString);

那么如何格式化最多两位小数的 double 值?如果最后一个位置包含零,则应省略零。

解决方案:

NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];
NSNumber *myValue = [NSNumber numberWithDouble:0.01234];
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]];
[doubleValueWithMaxTwoDecimalPlaces release];
doubleValueWithMaxTwoDecimalPlaces = nil;

最佳答案

在配置格式化程序时尝试添加以下行:

    [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];

关于iphone - 将 double 限制为两位小数,不带尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4026135/

相关文章:

iphone - UILongPressGestureRecognizer 不删除 View

android - 用 html5 编写离线移动网络应用程序有意义吗?

iphone - 在 UIScrollview 上停止动画

iphone - 在 UIViewController 上显示 clearColor UIViewController

iphone - 在 iPhone 应用程序中将日期保存到 SQLite3

iphone - 在 UIScrollView 中使用相当大的图像的 UIImageViews 使用的问题 dealloc'ing 内存

iphone - 从我的 iPhone 应用程序中删除项目时冒烟(或)爆炸动画

ios - 模拟器和 iPhone 6 plus 上的 iphone 套接字流缓冲区不同?

iphone - 游戏编程难题数学题

iphone - 使用 NSDateFormatter 解析 Twitter 字符串