Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact float value from a NSString

NSString *str = @"37.3336";
float f = [str floatValue];

f is 37.3335991.

Aside from rounding this myself, is there a way to get the exact float value from a NSString?

like image 470
Morrowless Avatar asked Jul 31 '11 09:07

Morrowless


2 Answers

Use [NSDecimalNumber decimalNumberWithString:locale:]. This will maintain the number in a decimal format rather than a binary format.

like image 95
Rob Napier Avatar answered Oct 18 '22 07:10

Rob Napier


Not easily. It's entirely possible that the number represented in the NSString has no exact representation as a primitive floating-point type.

If you know your input will never exceed a certain length, and don't need to be able to parse to a primitive floating-point type then you could use something like NSDecimalNumber (good for up to 38 digits) or implement a comparable utility yourself where you note the position of the decimal point, parse the number as an integer, and reinsert the decimal point at the correct location whenever you need to print it out.

Or if your input length is meant to be unconstrained then the only thing you can really try is using an arbitrary-precision arithmetic library.

Note that with any of these approaches, you still will not be able to construct a primitive floating-point value that is guaranteed to exactly match your input. If you need exact precision then you simply cannot rely upon float and double.

like image 45
aroth Avatar answered Oct 18 '22 08:10

aroth