objective-c 如何在Objective C中将float转换为int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/286756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a float to an int in Objective C?
提问by Nick Locking
Total newbie question but this is driving me mad! I'm trying this:
完全是新手问题,但这让我发疯!我正在尝试这个:
myInt = [myFloat integerValue];
but I get an error saying essentially integerValue doesn't work on floats.
但我收到一条错误消息,说本质上 integerValue 不适用于浮点数。
How do I do it?
我该怎么做?
回答by unwind
I'm pretty sure C-style casting syntax works in Objective C, so try that, too:
我很确定 C 风格的转换语法在 Objective C 中有效,所以也试试:
int myInt = (int) myFloat;
It might silence a compiler warning, at least.
至少,它可能会使编译器警告静音。
回答by Alnitak
what's wrong with:
有什么问题:
int myInt = myFloat;
bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)
请记住,这将使用默认舍入规则,即趋向于零(即 -3.9f 变为 -3)
回答by Hermann Klecker
int myInt = (int) myFloat;
Worked fine for me.
对我来说效果很好。
int myInt = [[NSNumber numberWithFloat:myFloat] intValue];
Well, that is one option. If you like the detour, I could think of some using NSString. Why easy, when there is a complicated alternative? :)
嗯,这是一种选择。如果您喜欢绕道而行,我可以想到一些使用 NSString 的方法。当有一个复杂的选择时,为什么容易?:)
回答by jmcharnes
You can also use C's lroundf(myFloat).
您也可以使用 C 的lroundf(myFloat).
An incredibly useful tip: In Xcode's editor, type your code as say
一个非常有用的提示:在 Xcode 的编辑器中,输入你的代码
myInt = roundf(someFloat);
then control/right-click on roundfand Jump to definition(or simply command-click).
然后控制/右键单击roundf并跳转到定义(或简单地单击命令)。
You will then clearly see the very long list of the functions availableto you. (It's impossible to remember them all, so just use this trick.)
然后,您将清楚地看到很长的可用功能列表。(不可能全部记住,所以只需使用这个技巧。)
For example, in the example at hand it's likely that lrintfis what you want.
例如,在手头的示例中,这很可能lrintf就是您想要的。
A further tip: to get documentation on those many functions. In your Terminal.app (or any shell - nothing to do with Xcode, just the normal Terminal.app) simply type man lrintfand it will give you full info. Hope it helps someone.
另一个提示:获取有关这些许多功能的文档。在您的 Terminal.app(或任何外壳程序 - 与 Xcode 无关,只是普通的 Terminal.app)中,只需键入man lrintf,它就会为您提供完整信息。希望它可以帮助某人。
回答by Matthew Schinckel
In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.
为了支持 unwind,请记住 Objective-C 是 C 的超集,而不是一种全新的语言。
Anything you can do in regular old ANSI C can be done in Objective-C.
您可以在常规旧 ANSI C 中执行的任何操作都可以在 Objective-C 中完成。
回答by Ben Leggiero
Here's a more terse approach that was introduced in 2012:
这是 2012 年引入的更简洁的方法:
myInt = @(myFloat).intValue;

