Not easy. It is possible that the number represented in NSString does not have an exact representation as a primitive floating point type.
If you know that your input will never exceed a certain length and will not need to parse a primitive type with a floating point, you can use something like NSDecimalNumber (useful for up to 38 digits) or implement a comparable utility yourself when you mark the decimal position dots, analyze the number as an integer and insert the decimal point in the right place when you need to print it.
Or, if your input length should be unlimited, the only thing you can really try is to use an arithmetic library of arbitrary precision.
Note that with any of these approaches, you still will not be able to build a primitive floating point value that is guaranteed to exactly match your input. If you need accurate precision, you simply cannot rely on float and double .
aroth
source share