2013-03-15 111 views
10

讓我知道如何對Objective-C中的2位小數進行圓整處理。如何對Objective-C中的2位小數進行圓整

我想這樣做。 (所有數字的下面的句子是浮點值)

•輪

10.118 => 10.12

10.114 => 10.11

•小區

10.118 => 10.12

•地板

10.114 => 10.11

感謝您檢查我的問題。

+3

你這樣做就像你在C中做的那樣:) – dasblinkenlight 2013-03-15 09:55:48

+0

你需要結果值是字符串還是保持浮動狀態? – coverback 2013-03-15 09:56:24

+0

http://stackoverflow.com/questions/10749483/how-to-convert-a-float-value-to-rounded-off-in-iphone-app/10749620#10749620 – 2013-03-15 09:59:33

回答

28

如果你確實需要數四捨五入,而不是僅僅提出時:

float roundToN(float num, int decimals) 
{ 
    int tenpow = 1; 
    for (; decimals; tenpow *= 10, decimals--); 
    return round(tenpow * num)/tenpow; 
} 

或總是到小數點後兩位:

float roundToTwo(float num) 
{ 
    return round(100 * num)/100; 
} 
+0

恩,這不適合我。它給了我一個六位小數的浮點數。 – 2013-08-13 16:25:21

+2

@TheJuicedWord:顯然,正確的NSLog/printf轉換說明符仍然需要爲'%.2f'。 – 2013-08-13 16:36:29

+1

@ user529758但仍然沒有解決實際的'float'未被正確舍入的事實。 – 2015-10-05 13:13:13

0
float roundedFloat = (int)(sourceFloat * 100 + 0.5)/100.0; 
+0

這對於負數不正確。 C標準庫中有一個'round()'函數。 – 2013-03-15 10:03:38

+0

是的,但是:1.在這個例子中只有正數,2。我的目標只是爲了展示這個想法;) – Gobra 2013-03-15 10:16:40

+1

我明白了你的觀點,但這不是這個想法。 – 2013-03-15 10:17:44

9

您可以使用以下將其格式化爲小數點後兩位的代碼

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
formatter.numberStyle = NSNumberFormatterDecimalStyle; 
formatter.setMaximumFractionDigits = 2; 
formatter.setRoundingMode = NSNumberFormatterRoundUp; 

NSString *numberString = [formatter stringFromNumber:@(10.358)]; 
NSLog(@"Result %@",numberString); // Result 10.36 
+0

我想OP想要*實際*輪數。 – 2013-03-15 10:01:48

+0

按照由@Takuy​​a給定的條件(10.118 => 10.12 10.114 => 10.11 •小區 10.118 => 10.12 •地板 10.114 => 10.11),我認爲這應該爲他工作。 – Suhaiyl 2013-03-15 10:05:55

+0

我的意思是,他不想*打印*取整值,而是取*取整取值。 – 2013-03-15 10:06:41