Search code examples
ioscocoansstringdoublelong-double

How to convert a NSString to long double?


I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

[myString doubleValue];

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

long double x = (long double)[@"3765765765E933" doubleValue];

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?


Solution

  • In fact the answer of mag_zbc is almost there. The last line is incorrect.

    Considering that the string has exponent, the correct is:

    - (long double)longDoubleValue {
      NSArray *array = [string componentsSeparatedByString:@"E"];
      long double mantis = (long double)[array[0] doubleValue];  
      long double exponent = (long double)[array[1] doubleValue];
      long double multiplier = powl(10.0L, exponent);
      return mantis * multiplier;
    }