%g 在 ios 中给出指数形式的值

%g gives Exponential Form of Value in ios

我的要求

有一个标签有 Price Value (Float Value)

如果是 -> 那么应该是

1232.200 -> 1232.2

1232.243 -> 1232.243

1232.00 -> 1232

到目前为止我做了什么

1) 使用 %.2f

lblPrice.text=[NSString stringWithFormat:@"%.2f",myValue];

但它总是在 1232.201232.241232.00 等点后分别给出 2 位数字...

2) 然后我将 %.2f 更改为 %g

lblPrice.text=[NSString stringWithFormat:@"%g",myValue];

这给了上述所有要求的完美价值,但是当价值超过某个水平时,它被转换成指数形式这样..

如果 myValue 是 1189243.609 那么结果是 1.18924e+06 我不想要..

有什么解决办法吗??? 提前致谢..

你可以一个一个的试试

lblPrice.text = [NSString stringWithFormat:@"%qi", myValue];

lblPrice.text = [NSString stringWithFormat:@"%.0f", myValue];

或查看以下link

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

我刚刚测试了下面的代码,它按照您的要求工作希望能有所帮助:

NSNumberFormatter *NumberFormate = [[NSNumberFormatter alloc] init];
[NumberFormate setRoundingIncrement:[NSNumber numberWithDouble:0.001]];
[NumberFormate setMaximumFractionDigits:4];
[NumberFormate setMinimumFractionDigits:0];

NSLog(@"232.200 IS %@", [NumberFormate stringFromNumber:[NSNumber numberWithFloat:1232.200]]);
NSLog(@"1232.243 IS %@", [NumberFormate stringFromNumber:[NSNumber numberWithFloat:1232.243]]);
NSLog(@"1232.00 IS %@", [NumberFormate stringFromNumber:[NSNumber numberWithFloat:1232.00]]);

它的输出是:

更新:

对于你的 0.50,如果你想像 0.5 那样输出,那么只需在现有代码中再添加一行,如下所示。

[NumberFormate setNumberStyle:NSNumberFormatterDecimalStyle];