可能重複:
How can I round a float value to 2 post decimal positions?回合浮點值至0.1(十位)
可以說我有3.46雙號。 我如何將它變成3.50? 我試圖
NSLog(@"res: %.f", round(3.46));
但它返回3.
可能重複:
How can I round a float value to 2 post decimal positions?回合浮點值至0.1(十位)
可以說我有3.46雙號。 我如何將它變成3.50? 我試圖
NSLog(@"res: %.f", round(3.46));
但它返回3.
做一些計算....
float f=3.46;
float num=f+0.05;//3.51
int intNum=num*10;//35
float floatNum=intNum/10.0;//3.5
NSLog(@"res: %.2f", floatNum); //3.50
下面的代碼可以幫助
i = roundf(10 * i)/10.0;
其中i爲您的浮點型變量
不,它不是... –
即使有變化,它仍然不完整 - 輸出將使用原始文章中的格式爲「3.5」。 – 2013-01-10 08:32:05
編輯答案請檢查.. –
如果你願意住與rounding rules from printf,那麼下面應該當呈現四捨五入足夠了:
NSLog(@"res: %.1f0", 3.46);
注意,0僅僅是被後添加正常字符值的格式到小數點的適當數字(1)。這種方法也可以與[NSString stringWithFormat:]
一起使用。
原始代碼導致「3」,因爲round
總是返回一個整數值。
YMMV;我甚至不使用iOS。
雖然其他問題會幫助完成部分任務,但它與其他問題並不完全相同。在這個特定的例子中,數字應該舍入到3.5(小數點後1位),然後在操作後顯示最後的0(例如'%0.2f'或任何它) - 記住前導/尾隨零實際上不是零的值(即3.5 == 3.50)。 – 2013-01-10 08:27:00