简体   繁体   中英

Objective C float to NSString

In my application I am having code like this

financialCost = [NSString stringWithFormat: @"%@",[valueFromBank objectForKey:@"Cost"]];
 
[valueFromBank objectForKey:@"Cost"] // This value comes from JSON through Websocket event.

Everything working fine. The problem I am facing is

When I get json value as 5 it is working fine When I get json value as 6.1 it is working fine

But strangely when I get the json value as 8.3 then it shows as 8.3100001200 For the value 9.1 it is shows 9.1000002200

I want to show 8.3 and 9.1 accurately.

Is there any solution for this problem.

Apart from the decoding trouble that even can happen with calculation of simple mathematical expressions. In deserialized JSON as dictionary decimals arrive as Objects and can be read as NSNumber.

// just an given example JSON as NSDictionary
NSDictionary *valueFromBank = @{@"Cost":@(8.3100001200), @"second":@9.1000002200, @"third":@"8.3100001200"};

NSNumber *numberCost = [valueFromBank objectForKey:@"Cost"];
NSLog(@"as NSNumber %@",numberCost);

NSNumber is 8.31000012 here as given in example dict.
The magic of NSNumber is, the object can be a written decimal NSString also. So that

NSNumber *numberCostV2 = [valueFromBank objectForKey:@"third"];

is still understood as NSNumber 8.31000012

float floatCost = [numberCostV2 floatValue];
NSLog(@"as float %f",floatCost);

float is 8.310000 here.

NSString *financialCost = [NSString stringWithFormat:@"%.2f",floatCost];
NSLog(@"as NSString withFormat %@", financialCost);

NSString in format is 8.31

What to learn from it?
Seems simple, but the golden rule is to convert in the last step, if possible or with exact accuracy as needed. And sometime NSString is helping you out and/or does it make worse.

NSDecimalNumber *decimal = [[NSDecimalNumber alloc] initWithDouble:8.124];
NSLog(@"as double %f and as NSString %@", [decimal doubleValue], [decimal stringValue]);

as double 8.124000 and as NSString 8.124000000000002048

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