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

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

问题描述

我想做一些数字舍入和转换为字符串以增强在Objective-C程序的输出。



我有一个float值,我想舍入到最接近的.5,然后使用它来设置标签上的文本。



例如:



1.4是一个字符串:



1.2是一个字符串:1



我花了一些时间虽然在谷歌寻找答案,但作为一个noob与Objective-C,我不知道要搜索什么!



谢谢,
Ash

解决方案

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

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

上面的测试用例适用于我的测试用例,但如果有人知道更好的方法这我有兴趣听到!


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

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.

For example:

1.4 would be a string of: 1.5

1.2 would be a string of: 1

0.2 would be a string of: 0

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, Ash

解决方案

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天全站免登陆