简体   繁体   English

目标 C 浮动到 NSString

[英]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当我得到 json 值为 5 时,它工作正常 当我得到 json 值为 6.1 时,它工作正常

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但奇怪的是,当我将 json 值设为 8.3 时,它显示为 8.3100001200 对于值 9.1,它显示为 9.1000002200

I want to show 8.3 and 9.1 accurately.我想准确地显示 8.3 和 9.1。

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.在反序列化的 JSON 中,字典小数作为对象到达,可以读取为 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. NSNumber 在此处为8.31000012 ,如示例 dict 中所示。
The magic of NSNumber is, the object can be a written decimal NSString also. NSNumber 的神奇之处在于,object 也可以是书面的十进制 NSString。 So that以便

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

is still understood as NSNumber 8.31000012还是理解为 NSNumber 8.31000012

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

float is 8.310000 here.浮动在这里是8.310000

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

NSString in format is 8.31 NSString 格式为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.有时 NSString 会帮助你和/或让它变得更糟。

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作为双 8.124000和作为NSString 8.124000000000002048

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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