简体   繁体   English

Objective-C-如何提高浮点数的精度

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

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. 假设我有一个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]. 如您所见,这里的精度仅为1。我想将其设置为6。我需要这样做,因为我将此值与从[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. 即使我在文本框中输入2504.6,也将增加5个精度,即2504.600098。 And when I compare these two values they appear to be not equal. 当我比较这两个值时,它们似乎不相等。

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. 如果您需要一个非常精确的非整数,请使用一个int(或long)并缩放它。 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 比较目标C中的float和double数据类型

Objective-C Float / Double precision Objective-C浮点/双精度

Make a float only show two decimal places 使浮点数仅显示两位小数

Comparing two float variables A and B using 'equal' operator is not very good idea, cause float numbers have limited precision. 使用“等于”运算符比较两个浮点变量A和B并不是一个好主意,因为浮点数的精度有限。 The best way to compare floats is 比较浮点数的最佳方法是

fabs(A - B) < eps  

where eps is some very small value, say 0.0001 其中eps是一些非常小的值,例如0.0001

If you're operating with strings that represent the float values you can just compare strings and not the numbers. 如果使用表示浮点值的字符串进行操作,则只能比较字符串而不是数字。

You can compare the numbers using NSDecimalNumber : 您可以使用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM