溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

綜合網(wǎng)上的各種不靠譜的算法,自己寫的四舍五入方法

發(fā)布時間:2020-07-24 04:13:40 來源:網(wǎng)絡 閱讀:248 作者:38734603 欄目:開發(fā)技術
//單元測試通過
/**
 *   四舍五入并保留N位小數(shù)
 *
 *  @param number    數(shù)值字符串
 *  @param afterPoint 第幾位小數(shù)
 *
 *  @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];

}


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI