How to convert NSString to long double?

I am dealing with a value long double

that can make a huge difference.

At one time this number is represented as NSString

, and I need to convert it to long double

. I see that only I have the API

[myString doubleValue];

      

I can't see longDoubleValue

.

Trying to convert this number with doubleValue

...

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

      

gives me inf

, and the number shown is a legal value long double

as these numbers can reach 1.18973149535723176502E+4932

.

How to do it?

+3


source to share


4 answers


In fact, there is mag_zbc

almost no answer . The last line is wrong.

Considering the line has an exponent, the correct one 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;
}

      

0


source


Maybe create a category on NSString yourself

NSArray *array = [myString componentsSeparatedByString:@"E"];
long double mantis = (long double)[array[0] doubleValue];
long double exponent = (long double)[array[1] doubleValue]; 
return mantis * exponent;

      



There may be data loss though

edit
It would appear to be long double

the same size on iOS as double

. You may need a special class to store such large numbers.

+2


source


Perhaps you could do:

long double s = strtold(myString.UTF8String, NULL);

      

but if sizeof(long double)

matches sizeof(double)

as mag_zbc says you can get Inf

.

If you want to traverse a route pow()

, there is powl()

one that takes and returns long double

s.

+1


source


You can do this using the C library function sscanf

. Here's an example of an Objective-C wrapper:

long double stringToLongDouble(NSString *str)
{
   long double result = 0.0L;
   int ret = sscanf(str.UTF8String, "%Lg", &result);
   if (ret != 1)
   {
      // Insert your own error handling here, using NSLog for demo
      NSLog(@"stringToLongDouble: could not parse '%@' as long double", str);
      return 0.0L;
   }
   return result;
}

      

Refund sscanf

will be made 1

if successful. For possible errors see the documentation ( man 3 scanf

in terminal) and you need to decide how to deal with this, the above example just does NSLog

.

Note. Size and accuracy long double

may vary depending on platform / OS version. The above has been tested using your value on El Capitan and iOS 10 (simulator only) using Xcode 8.

NTN

0


source







All Articles