I have a number stored in an NSNumber
which I would like to put into a long double
, like so:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMinimumSignificantDigits:5];
NSNumber * myNumber = [f numberFromString:@"1.1234567899"];
long double lnumber = mynumber;
NSLog(@"%Lf ",lnumber);
An NSNumber
is an Objective-C object, and long double
is a primitive type. You can't assign an object to a primitive-typed variable. If you want the numerical value that is stored in the NSNumber
, you need to use one of its methods to retrieve it:
long double lnumber = [myNumber doubleValue];
There is no provision for storing a long double
in an NSNumber
; the largest floating-point type is simply double
. It seems that long double
may be the same size as double
on iOS anyways: see this Apple Support Forum thread .
As ThomasW mentioned , NSDecimalNumber
, a fixed-point number class, offers both more precision (up to 38 digits) and accuracy than NSNumber
. There is still no way to get a long double
out of it, though; you would have to do all your math only with NSDecimalNumber
s to retain the precision.
Your question title originally mentioned NSInteger
as well, although the body didn't, so let me add this note. An NSInteger
is a primitive type, like long double
, so you can in fact assign from one to the other.
NSInteger myInteger = 10000;
long double lnumer = myInteger;
However, because it is an integer, it can't have a fractional part.
As far as I know the best you are going to get is a double value.
long double lnumber = [mynumber doubleValue];
You can also do this if the value is in a string to begin with
NSString* sval = @"1.1234567";
double dval = [sval doubleValue];
Unfortunately you can't. As NSNumber Class Reference says, NSNumber
supports double
and float
but not long double
.
If you need high precision you could use NSDecimalNumber
, but it doesn't support long double
either.
尝试输出数字:
long double lnumber = (long double) mynumber;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.