我的字符串有一个双倍值2.344
。现在我想要从服务器获得这个数字的小数位数。所以我maxdecimalPlaces
是2
然后如果2.34
为maxdecimalplaces
,我希望号码为3
,那么我想将号码设为2.344
。
我不想使用[NSString StringwithFormat:@"%.2f",value];
因为小数位数是动态的。请告诉我如何解决这个问题,
答案 0 :(得分:2)
我的maxdecimalPlaces是2然后我想将数字设为2.34如果maxdecimalplaces是3那么我想将数字设为2.344
使用setMaximumFractionDigits:
并传递maxdecimalPlaces
float inputValue = 2.344;
NSNumberFormatter *Formatter = [[NSNumberFormatter alloc] init];
[Formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[Formatter setMaximumFractionDigits:maxdecimalPlaces];
NSString *finalOutput = [Formatter stringFromNumber:[NSNumber numberWithFloat:inputValue]];
NSLog(@"finalOutput: %@", finalOutput)
答案 1 :(得分:0)
这是使用NSNumberFormatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:@(0.3333)]); // output expected .33
希望它对你有所帮助。