//單元測試通過
/**
* 四舍五入并保留N位小數
*
* @param number 數值字符串
* @param afterPoint 第幾位小數
*
* @return 處理后結果
*/
+(NSString *)halfUpDecimalNumber:(NSString *)number afterPoint:(int)position
{
/*
Mode的枚舉類型
NSRoundPlain, // 四舍五入
NSRoundDown, // 只舍不入
NSRoundUp, // 不舍只入
NSRoundBankers //
*/
if ([number length]==0) {
return @"";
}
NSDecimalNumber *ouncesDecimal = [NSDecimalNumber decimalNumberWithString:number];
NSString *formatStr=@"0.";
for (int i=0; i<position; i++) {
formatStr=[formatStr stringByAppendingString:@"0"];
}
NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];
[doubleValueWithMaxTwoDecimalPlaces setPaddingCharacter:@""];
[doubleValueWithMaxTwoDecimalPlaces setPaddingPosition:NSNumberFormatterPadAfterSuffix];
[doubleValueWithMaxTwoDecimalPlaces setFormatWidth:position];
[doubleValueWithMaxTwoDecimalPlaces setPerMillSymbol:@""];
[doubleValueWithMaxTwoDecimalPlaces setAlwaysShowsDecimalSeparator:YES];
[doubleValueWithMaxTwoDecimalPlaces setGroupingSeparator:@""];
[doubleValueWithMaxTwoDecimalPlaces setRoundingMode:NSNumberFormatterRoundHalfUp];
[doubleValueWithMaxTwoDecimalPlaces setPositiveFormat:formatStr];
return [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:ouncesDecimal];
}免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。