標籤:
http://blog.sina.com.cn/s/blog_71715bf801017nyw.html
方法一:
-(NSString *)notRounding:(float)price afterPoint:(int)position{
NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *ouncesDecimal;
NSDecimalNumber *roundedOunces;
ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
[ouncesDecimal release];
return [NSString stringWithFormat:@"%@",roundedOunces];
}
介紹一下參數:
price:需要處理的數字,
position:保留小數點第幾位,
然後調用
float s =0.126;
NSString *sv = [self notRounding:s afterPoint:2];
NSLog(@"sv = %@",sv);
輸出結果為:sv = 0.12
接下來介紹NSDecimalNumberHandler初始化時的關鍵參數:decimalNumberHandlerWithRoundingMode:NSRoundDown,
NSRoundDown代表的就是 只舍不入。
scale的參數position代表保留小數點後幾位。
如果只入不舍怎麼辦,比如,float 0.162 想要得到0.17該怎麼做?,在開發文檔上有這樣一個表,是按照保留小數點後一位處理的。相信大家一看就明白了:
方法二:
1、round(12345.6789) 結果為:12346
2、round(12345.6789*100)/100 結果為:12345.68
第二個是我要的結果,但是我不明白這麼個簡單的四捨五入要搞的這麼複雜,應該有更好的吧,我記得在其他語言裡用:round(12345.6789,2) 就可以實現四捨五入到兩位小數。
IOS開發之----四捨五入問題