NSString轉換float的精度問題

NSString 轉換 float 的精度問題, 換double類型可以解決


@”0.01” 轉換成float時, 經常會變成 0.009999799 這種形式, 因爲float類型無法精準保存, 系統會選一個接近的值來代替.

而double類型則可以有更好的精度.

http://stackoverflow.com/questions/9328260/converting-nsstring-to-float-adds-in-decimal-places

Your issue seems to be that you don’t understand how floats are stored in memory and don’t know that floats aren’t precise.

Exact values often can’t be stored and so the system picks the closest number it can to represent it. If you look carefully, you can see that each of the outputted numbers is very close to your inputted values.

For better accuracy, try using double instead. Double does encounter the same problems, but with better precision. Floats have about 6 significant digits; doubles have more than twice that.

source

Here are some other StackOverflow answers and external articles you should read:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章