在iOS中将值转换为尽可能多的小数位数?

时间:2017-03-30 13:19:43

标签: ios objective-c floating-point

我的字符串有一个双倍值2.344。现在我想要从服务器获得这个数字的小数位数。所以我maxdecimalPlaces2然后如果2.34maxdecimalplaces,我希望号码为3,那么我想将号码设为2.344

我不想使用[NSString StringwithFormat:@"%.2f",value]; 因为小数位数是动态的。请告诉我如何解决这个问题,

2 个答案:

答案 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

希望它对你有所帮助。