当前位置:
首页 >
iOS知识小集·NSNumber to NSString出错啦
发布时间:2025/7/14
54
豆豆
生活随笔
收集整理的这篇文章主要介绍了
iOS知识小集·NSNumber to NSString出错啦
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
起因
某一次准备把一个NSNumber显示在lable上。
NSString *text = [NSString stringWithFormat:@"%@",value]; 复制代码嗯。很完美。
问题
写下如下代码:
self.label.text = [NSString stringWithFormat:@"%@",@(8.0)];self.label1.text = [NSString stringWithFormat:@"%@",@(8.1)];self.label2.text = [NSString stringWithFormat:@"%@",@(8.2)];self.label3.text = [NSString stringWithFormat:@"%@",@(8.3)]; 复制代码结果:
8.2,8.3这两个数显示的是什么鬼???!!!解决办法
既然直接%@不行,那么我们把它转化成double吧。
self.label.text = [NSString stringWithFormat:@"%f"8.0];self.label1.text = [NSString stringWithFormat:@"%f",8.1];self.label2.text = [NSString stringWithFormat:@"%f",8.2];self.label3.text = [NSString stringWithFormat:@"%f",8.3]; 复制代码结果:
啊,为什么这么长!!本来想用 NSString *text = [NSString stringWithFormat:@"%.01f",8.2]; 复制代码这样的方法来固定在小数点后1位的。可是,产品经理不答应啊!!他说:“这个数字是版本号的意思,所以要显示8.2,8.21,8.321这样。”
好吧,我们稍作修改就好。
self.label.text = [NSString stringWithFormat:@"%g",8.1];self.label1.text = [NSString stringWithFormat:@"%g",8.2];self.label2.text = [NSString stringWithFormat:@"%g",8.23];self.label3.text = [NSString stringWithFormat:@"%g",8.321]; 复制代码结果:
好吧,这下好了吧!?总结
以上是生活随笔为你收集整理的iOS知识小集·NSNumber to NSString出错啦的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 吴恩达:现在很多所谓的AI公司,其实都不
- 下一篇: 产业结盟 跨界共赢 | 新华三成为“中国