How to do math on NSNumber
16,869
Solution 1
You need to box integer or float value to store it in 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
Solution 2
You should keep the value in float first and the need to create the NSNumber from it.
NSNumber *reading = [NSNumber numberWithFloat:someValue];
float newNum = [reading floatValue] * 100;
reading = [NSNumber numberWithFloat:newNum];
Author by
sdknewbie
Updated on June 05, 2022Comments
-
sdknewbie almost 2 years
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.
Here is my code:
NSNumber *reading = [some value]; reading = [reading floatValue] * 100;
However, I get "Assigning to NSNumber *_strong from incompatible type float"
I am new to working NSNumber objects and struggle to understand how to display my sensor reading as a percentage for the user. Ex: 75%
Thanks for any help
-
John about 11 years@sdknewbiew But I think it is more important "do you understand AnoopVaidya code does what you wanted?"
-
Anoop Vaidya about 11 years@John: Nice question. I think he would have analysed between my and apurv's code. similar code in new and old style obj-c. Nothing much difference. what you say?
-
Apurv about 11 years@AnoopVaidya : Yes. No difference. You were fast enough to post. When I submitted the answer, your answer was already there.
-
Nico about 11 yearsWhy would you box up
someValue
just to unbox the value again on the very next line? Just usesomeValue
in the multiplication expression. -
Anoop Vaidya about 11 years@Devfly: To show the result as : 75%, check in the question. one % will not be shown, therefore two is used.
-
Motti Shneor almost 4 yearsAlthough beautiful answer, and accepted by OP, it doesn't actually answer the main title of the question, because math is NOT done on the NSNumber level, but rather on the primitive types un-boxed out of it, and a new NSNumber is created boxing the primitive result. This is going from Obj-C to C and back to Obj-C. Isn't there a direct way?