Objective-C - How to increase the precision of a float number

青春壹個敷衍的年華 提交于 2019-12-20 04:07:31

问题


Can someone please show me the way to set the precision of a float number to desired length. Say I have a number 2504.6. As you see the precision here is only 1. I want to set it to six.I need this because I compare this value with the value obtained from [txtInput.text floatValue]. And even if I enter 2504.6 to the text box it will add 5 more precisions and will be 2504.600098. And when I compare these two values they appear to be not equal.


回答1:


You can compare the numbers using NSDecimalNumber:

NSDecimalNumber *number = [NSDecimalNumber numberWithFloat:2504.6f];
NSDecimalNumber *input = [NSDecimalNumber decimalNumberWithString:txtInput.text];
NSComparisonResult result = [number compare:input];

if (result == NSOrderedAscending) {
    // number < input
} else if (result == NSOrderedDescending) {
    // number > input
} else {
    // number == input
}



回答2:


Floats are approximates. The way floats are stored does not allow for arbitrary precision. Floats (and doubles) are designed to store very large (or small) values, but not precise values.

If you need a very precise non-integer number, use an int (or long) and scale it. You could even write your own object class to handle that.

They won't appear to be equal

Btw this question has been asked before

Comparing float and double data types in objective C

Objective-C Float / Double precision

Make a float only show two decimal places




回答3:


Comparing two float variables A and B using 'equal' operator is not very good idea, cause float numbers have limited precision. The best way to compare floats is

fabs(A - B) < eps  

where eps is some very small value, say 0.0001

If you're operating with strings that represent the float values you can just compare strings and not the numbers.



来源:https://stackoverflow.com/questions/9455493/objective-c-how-to-increase-the-precision-of-a-float-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!