Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save a float to nsnumber with just two decimals

I'm trying to save a float to an nsnumber but i just want to save it with two decimal places. I know I can do it by converting to an NSString first using this code

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

but seems clumsy. All I want to do is convert

float numb = 23.25454 into NSNumber 23.25
like image 316
vboombatz Avatar asked Feb 03 '26 15:02

vboombatz


2 Answers

Use this

float numb = 23.25454;

NSNumber *num = @((int)(numb*100)/100.0);
like image 134
malex Avatar answered Feb 05 '26 08:02

malex


Just round it using any of these functions

float rounded = round(val * 100) / 100;
float rounded_down = floorf(val * 100) / 100;
float nearest = floorf(val * 100 + 0.5) / 100;
float rounded_up = ceilf(val * 100) / 100;
like image 37
Merlevede Avatar answered Feb 05 '26 06:02

Merlevede