Objective-C 中的舍入数字 [英] Rounding numbers in Objective-C

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

问题描述

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

I'm trying to do some number rounding and conversion to a string to enhance the output in an Objective-C program.

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

I have a float value that I'd like to round to the nearest .5 and then use it to set the text on a label.

例如:

1.4 将是一个字符串:1.5

1.4 would be a string of: 1.5

1.2 将是一个字符串:1

1.2 would be a string of: 1

0.2 将是一个字符串:0

0.2 would be a string of: 0

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

I've spent a while looking on Google for an answer but, being a noob with Objective-C, I'm not sure what to search for! So, I'd really appreciate a pointer in the right direction!

谢谢,灰

推荐答案

感谢大家的指点,我已经想出了一个解决方案:

Thanks for the pointers everyone, I've managed to come up with a solution:

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];

以上适用于我扔给它的测试用例,但如果有人知道更好的方法来做到这一点,我很想听听!

The above works for the test cases I threw at it, but if anyone knows a better way to do this I'd be interested to hear it!

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

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