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?
Use [NSDecimalNumber decimalNumberWithString:locale:]
. This will maintain the number in a decimal format rather than a binary format.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With