日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

iOS知识小集·NSNumber to NSString出错啦

發布時間:2025/7/14 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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出错啦的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。