Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 406
sdknewbie Avatar asked Mar 15 '13 16:03

sdknewbie


2 Answers

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

like image 125
Anoop Vaidya Avatar answered Oct 14 '22 17:10

Anoop Vaidya


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];
like image 29
Apurv Avatar answered Oct 14 '22 19:10

Apurv