天天看點

IOS開發之----四舍五入問題

方法一:

-(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該怎麼做?,在開發文檔上有這樣一個表,是按照保留小數點後一位處理的。相信大家一看就明白了:

IOS開發之----四舍五入問題

方法二:

1、round(12345.6789) 結果為:12346

2、round(12345.6789*100)/100 結果為:12345.68

第二個是我要的結果,但是我不明白這麼個簡單的四舍五入要搞的這麼複雜,應該有更好的吧,我記得在其他語言裡用:round(12345.6789,2) 就可以實作四舍五入到兩位小數。

繼續閱讀