简体   繁体   中英

Converting double to string return strange value in objective c

I have an NSDictionary which consist of multiple key/pair values. One of them consist double value.

NSNumber *goalValue = [info objectForKey:@"goalValue"];

I put breakpoint and I found that goalValue store the normal value that I need. 在此处输入图片说明

and just below I convert it to NSSting like

NSString *stringValue=[goalValue stringValue];

and this stringValue store very strange value.

在此处输入图片说明

Guys please help me. I am totally puzzled, I did goggle but nothing change. Please help me. Thanks in advance.

The method stringValue will convert the NSNumber to string by internally calling descriptionWithLocale: with locale as nil and this method in turn will call initWithFormat:locale: ,

From Apple docs,

To obtain the string representation, this method invokes NSString's initWithFormat:locale: method, supplying the format based on the type the NSNumber object was created with:

在此处输入图片说明

So format specifier used for double is %0.16g (ie 16 digit precision) hence the value 98.09999999999999

I'd suggest using NSNumberFormatter ,

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2]; //2 decimal places, change this as required.
NSString *string = [numberFormatter stringFromNumber:goalValue];

Hope that helps!

To prevent this behavior, I suggest using NSDecimalNumber (also this is from my experience best format when dealing with very precise amounts)

NSDecimalNumber *doubleDecimal = [[NSDecimalNumber alloc] initWithDouble:[info objectForKey:@"goalValue"]];

for two digits formatting, use numberFormatter

NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
 [nf setMinimumFractionDigits:2];
 [nf setMaximumFractionDigits:2];
NSString *stringValue  = [nf stringFromNumber:doubleDecimal]

Its showing the rounded value so you can round the value to single digit using NSNumberFormatter .

 NSNumberFormatter *fomatter = [[NSNumberFormatter alloc] init];
    [fomatter setMaximumSignificantDigits:2];

    NSString *stringValue=[fomatter stringFromNumber:goalValue];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM