Objective-C中的舍入数字

Ash*_*Ash 74 macos formatting cocoa objective-c rounding

我正在尝试进行一些数字舍入和转换为字符串以增强Objective-C程序中的输出.

我有一个浮点值,我想要舍入到最近的.5然后用它来设置标签上的文本.

例如:

1.4将是一串:1.5

1.2将是一串:1

0.2将是一个字符串:0

我花了一段时间在Google上寻找答案但是,作为Objective-C的菜鸟,我不知道该搜索什么!所以,我真的很感激指向正确的方向!

谢谢,阿什

Ash*_*Ash 100

感谢大家的指点,我设法提出了一个解决方案:

float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
[formatter release];
Run Code Online (Sandbox Code Playgroud)

以上是我投入的测试用例,但如果有人知道更好的方法,我会有兴趣听到它!

  • 如果将其输出到文本字段,则只需将格式化程序附加到字段即可. (7认同)

Dur*_*n.H 36

float floatVal = 1.23456;
Run Code Online (Sandbox Code Playgroud)

四舍五入

int roundedVal = lroundf(floatVal); 

NSLog(@"%d",roundedVal);
Run Code Online (Sandbox Code Playgroud)

围捕

int roundedUpVal = ceil(floatVal); 

NSLog(@"%d",roundedUpVal);
Run Code Online (Sandbox Code Playgroud)

四舍五入

int roundedDownVal = floor(floatVal);

NSLog(@"%d",roundedDownVal);
Run Code Online (Sandbox Code Playgroud)


ker*_*emk 32

NSString *numberString = [NSString stringWithFormat:@"%f", round(2.0f * number) / 2.0f];
Run Code Online (Sandbox Code Playgroud)


小智 24

使用lroundf()将float舍入为整数,然后将整数转换为字符串.


小智 11

NSString *numberString = [NSString stringWithFormat:@"%d",lroundf(number)];
Run Code Online (Sandbox Code Playgroud)


hbw*_*hbw 8

我建议使用NSNumberFormatter.


Lal*_*hna 5

一个简单的方法:

float theFloat = 1.23456;
int rounded = roundf(theFloat); NSLog(@"%d",rounded);
int roundedUp = ceil(theFloat); NSLog(@"%d",roundedUp);
int roundedDown = floor(theFloat); NSLog(@"%d",roundedDown);
// Note: int can be replaced by float
Run Code Online (Sandbox Code Playgroud)