ios - 抑制不必要的零

标签 ios objective-c iphone ipad stringwithformat

我想用 double 值创建一个带有 stringWithFormat 的字符串,最后没有不必要的零。

例子:

  1. [NSString stringWithFormat:@"%.8f",2.344383933];

  2. [NSString stringWithFormat:@"%.8f",2.0];

预期结果:

  1. 2.344383933

  2. 2

哪种格式是正确的?

谢谢。

最佳答案

使用NSNumberFormatter

[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",0]]

示例:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

NSLog(@"1: %@",[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",2.344383933]]);
NSLog(@"2: %@",[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",2.0]]);

结果:

1: 2.344383933

2: 2

关于ios - 抑制不必要的零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843470/

相关文章:

ios - TextField 和 Button 没有出现在容器 View 中?

objective-c - 重新分配 block objective-c

iphone - 使用 NSString 作为 NSString 数组?

objective-c - 如何使 super 成为 NSTimer 的目标?

objective-c - iOS:使用 NSXMLParser 从 HTTP 解析 xml

ios - 在 iOS 中绘制到已加载的 UIImage

objective-c - NSTask 失败 22 终止临时进程 cocoa

iphone - Objective-C 中自定义对象的分组

ios - 尝试在 Swift 中制作圆形 UIView 时出错

ios - WebKit 音频在 iOS 6 (iPhone 5) 上第一次在电源循环后失真