[英]How to do math on NSNumber
I am trying to take a reading off a sensor and display it as a percentage. 我试图读取传感器并将其显示为百分比。 [some value] will always be between 0 and 1.
[某些值]将始终介于0和1之间。
Here is my code: 这是我的代码:
NSNumber *reading = [some value];
reading = [reading floatValue] * 100;
However, I get "Assigning to NSNumber *_strong from incompatible type float" 但是,我得到“从不兼容的类型float分配给NSNumber * _strong”
I am new to working NSNumber objects and struggle to understand how to display my sensor reading as a percentage for the user. 我是新工作的NSNumber对象,并且很难理解如何以用户的百分比显示我的传感器读数。 Ex: 75%
例如:75%
Thanks for any help 谢谢你的帮助
You need to box integer or float value to store it in NSNumber, 你需要使用整数或浮点值来存储它在NSNumber中,
as: 如:
NSNumber *reading = @(10.123);
reading = @([reading floatValue] * 100);
After this, you can print/convert it into string as : 在此之后,您可以将其打印/转换为字符串:
NSString *display=[NSString stringWithFormat:@"%@%%",reading];
NOTE %% double percentage symbols 注意%%双倍百分比符号
You should keep the value in float first and the need to create the NSNumber from it. 您应该首先将值保留在float中,并且需要从中创建NSNumber。
NSNumber *reading = [NSNumber numberWithFloat:someValue];
float newNum = [reading floatValue] * 100;
reading = [NSNumber numberWithFloat:newNum];
I dont like to write multi line code because i am a bit lazy to multiline code writing. 我不喜欢写多行代码,因为我对多行代码编写有点懒惰。 I am always looking for compressed solutions.
我一直在寻找压缩解决方案。 Please find below the following solutions.
请在下面找到以下解决方案。
float testValue=5.00032;
NSString *resultValue=[NSString stringWithFormat:@"%@%%",[NSNumber numberWithFloat:(testValue*100)]];
Above solution is for float value. 以上解决方案是浮动值。 If you want provide input as integer value,Please replace the "numberWithFloat" with "numberWithInt".
如果要将输入作为整数值提供,请将“numberWithFloat”替换为“numberWithInt”。
I hope that this solution will help you. 我希望这个解决方案能帮到你。 Thanks.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.