简体   繁体   English

NSNumber十进制转换为C原始值?

[英]NSNumber decimal to C primitive value?

I want to convert a decimal NSNumber to an int or other form which I can do math with. 我想将小数的NSNumber转换成可以做数学运算的int或其他形式。 Here's the annotated code for my project: 这是我项目的注释代码:

NSNumber *Left = [left valueForOutputKey:@"Y"];

This line gets a Quartz Composer Outlet, usually with a value around 0.512. 该行将获得一个Quartz Composer插座,其值通常为0.512左右。

Basically, I want to multiply this by 10, and then do some operations like greater than and less than to see which range it is in. 基本上,我想将此乘以10,然后执行一些操作,例如大于和小于,以查看其在哪个范围内。

Since it looks like you're dealing with a fractional component, you want to convert it to a float or a double to perform your operations, depending on how big you expect that value to be. 由于看起来您正在处理小数部分,因此您希望将其转换为浮点数或双精度数以执行操作,具体取决于您希望该值的大小。 A float should be fine unless you're dealing with ridiculously large or precise numbers. 除非您要处理数量庞大或精确的数字,否则浮点数应该没问题。 Here's how it would look, for example: 例如,这是它的外观:

float lValue = [[left valueForOutputKey:@"Y"] floatValue];

lValue *= 10;

if (lValue < 10) {
    // do whatever
}
else if (lValue > 50) {
    // do whatever
}

Then to store the value back in your outlet or whatever, you pack it back into a NSNumber: 然后要将值存储回您的出口或其他任何地方,请将其包装回NSNumber中:

NSNumber *newValue = [NSNumber numberWithFloat:lValue];

[left setValue:newValue forKey:@"Y"];

You may have to convert newValue into a string to display it in a control, just use [newValue stringValue] to do that. 您可能需要将newValue转换为字符串才能在控件中显示,只需使用[newValue stringValue]即可。

Use one of the methods of NSNumber : 使用NSNumber的方法之一:

int leftInt = [Left intValue];
float leftFloat = [Left floatValue];
double leftDouble = [Left doubleValue];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM