在objective-c中舍入一个浮点数 [英] Rounding a float number in objective-c

查看:125
本文介绍了在objective-c中舍入一个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个简单的函数可以使用这样的示例。
我有一个

 浮点值= 1.12345; 

我想用

  float value2 = [roundFloat value:value decimal:3]; 
NSLog(@value2 =%f,value2);

我得到1.123
是否有任何 / code>或者默认的函数,或者我应该为这种类型的计算写一个代码块?



感谢您的帮助提前b $ b

解决方案使用 NSLog(@%f,theFloat)总是输出六位小数,例如:

  float theFloat = 1; 
NSLog(@%f,theFloat);

输出:

  1.000000 

换句话说,您永远不会得到 1.123通过使用 NSLog(@%f,theFloat)



小数点后三位:

  float theFloat = 1.23456; 
float newFLoat =(int)(theFloat * 1000.0)/ 1000.0;
NSLog(@%f,newFLoat);

输出:

  1.234000 

舍入小数点后三位(使用 roundf / lroundf() / ceil() / floor )):

  float theFloat = 1.23456; 
float newFLoat =(int)(roundf(theFloat * 1000.0))/ 1000.0;
NSLog(@%f,newFLoat);

输出:

  1.235000 

小数点后三位(脏方式):

  float theFloat = 1.23456; 
NSString * theString = [NSString stringWithFormat:@%。3f,theFloat];
float newFloat = [theString floatValue];
NSLog(@%@,theString);
NSLog(@%f,newFloat);

输出:

  1.235 
1.235000


I want to know if there is a simple function that I can use such this sample. I have a

float value = 1.12345;

I want to round it with calling something like

float value2 = [roundFloat value:value decimal:3];
NSLog(@"value2 = %f", value2);

And I get "1.123" Is there any Library or default function for that or I should write a code block for this type of calculations?

thank for your help in advance

解决方案

Using NSLog(@"%f", theFloat) always outputs six decimals, for example:

float theFloat = 1;
NSLog(@"%f",theFloat);

Output:

1.000000

In other words, you will never get 1.123 by using NSLog(@"%f", theFloat).

Cut-off after three decimals:

float theFloat = 1.23456;
float newFLoat = (int)(theFloat * 1000.0) / 1000.0;
NSLog(@"%f",newFLoat);

Output:

1.234000

Round to three decimals (using roundf() / lroundf() / ceil() / floor()):

float theFloat = 1.23456;
float newFLoat = (int)(roundf(theFloat * 1000.0)) / 1000.0;
NSLog(@"%f",newFLoat);

Output:

1.235000

Round to three decimals (dirty way):

float theFloat = 1.23456;
NSString *theString = [NSString stringWithFormat:@"%.3f", theFloat];
float newFloat = [theString floatValue];
NSLog(@"%@",theString);
NSLog(@"%f",newFloat);

Output:

1.235
1.235000

这篇关于在objective-c中舍入一个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆