将包含小数的NSString舍入为两位小数

时间:2015-01-13 20:24:00

标签: ios decimal

鉴于NSString“1.625”,我想将其舍入为“1.63”。 我这样做是怎么做到的?

这就是我现在所拥有的:

NSString *rateString = [NSString stringWithFormat:@"%.2f", [@"1.63" doubleValue]];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
item.rate = [f numberFromString:rateString];;

但是,doubleValue会将1.625转换为1.6249999999 所以当我用@“%。2f”将它四舍五入到两位小数时,我最终得到1.62!

2 个答案:

答案 0 :(得分:1)

如果你想要舍入到最接近的百分之一,乘以100,增加.5并除以100.然后得到该值的最低点。

double rate = [@"1.625" doubleValue];
double roundedNumber = floor(rate * 100 + 0.5) / 100;

NSString *rateString = [NSString stringWithFormat:@"%.2f", roundedNumber];
NSLog(@"rate: %@", rateString);

运行它然后输出结果:

2015-01-13 15:41:08.702 Sandbox[22027:883332] rate: 1.63

答案 1 :(得分:1)

如果你需要高精度,你真正需要的是NSDecimalNumber类如果不需要配置所有细节可以与NSDecimalNumberHandler结合,或者NSDecimalNumberBehaviors如果需要绝对控制。这是保持2个十进制数字(处理程序init中的'scale'值)的最快解决方案:

NSDecimalNumberHandler *handler = [[NSDecimalNumberHandler alloc]initWithRoundingMode:NSRoundBankers
                                                                                scale:2
                                                                     raiseOnExactness:NO
                                                                      raiseOnOverflow:NO
                                                                     raiseOnUnderflow:NO
                                                                  raiseOnDivideByZero:NO];

[NSDecimalNumber setDefaultBehavior:handler];

NSString *string = @"1.63";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:string];

NSDecimalNumber docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumber_Class/index.html

NSDecimalNumberHandler docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumberHandler_Class/index.html

NSDecimalNumberBehaviors docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSDecimalNumberBehaviors_Protocol/index.html