如何只舍不入。比如 float price = 0.126,怎么樣才能得到0.12?
當然,通過字符串截取的辦法肯定也能達到相同的效果。但是就是這么一個簡單的問題要通過一些判斷和截取才能獲得結果,總感覺有點笨拙。
下面先給出該問題的解決辦法:
-(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) 就可以實現四舍五入到兩位小數。
方法三:
NSTimeInterval Interval = 305.721125;
NSInteger timeInt = [[NSString stringWithFormat:@"%.0f", Interval] integerValue];
Interval:305.721125
timeInt:306
1 |
NSLog(@ "%@" , [NSString stringWithFormat:@ "%.0f" , 1.0003]); |
2 |
NSLog(@ "%@" , [NSString stringWithFormat:@ "%.0f" , 1.9003]); |
3 |
NSLog(@ "%@" , [NSString stringWithFormat:@ "%.0f" , 1.5003]); |
4 |
NSLog(@ "%@" , [NSString stringWithFormat:@ "%.0f" , 1.4003]); |
1 |
1 |
1 |
1 |
1 |
2 |
1 |
2 |
1 |
1 |
方法四:
1. / //Test "/" |