How to do math on NSNumber

sdknewbie picture sdknewbie · Mar 15, 2013 · Viewed 16.7k times · Source

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

Answer

Anoop Vaidya picture Anoop Vaidya · Mar 15, 2013

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