# How to round of CGFloat value

11,636

## Solution 1

Try this........

``````NSLog(@"SCALE : %.3f", scale);
NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];
``````

## Solution 2

Sounds like you want a rounded number that is still a float but only out to 3 decimals and not just for display purposes? Is that what you are asking? IEEE floating point numbers are a real pain. You can assign foo = 1.5 and then you'll end up with 1.499999999 and if you then go say `if ( foo == 1.5 )` it'll fail. Just seems like a bug to me, but there's long descriptions about why this is "correct" on the net. Seems like ivory-tower-correct and real-world-useless to me.

So, some possibilities. I wonder if multiplying by 1000 and then rounding up to the integer value and then dividing by 1000 will work... Course the same IEEE floating-bug, sorry spec might still bite you... worth a try.

Got myself curious and wrote a quick test:

``````CGFloat foo = 0.124979;
NSLog(@"foo is: %f", foo );
NSInteger ifoo = ceil(foo * 1000.0);
foo = ifoo / 1000.0;
NSLog( @"ifoo is: %d, and back to foo is: %f", ifoo, foo );
``````

outputs this (in the simulator anyway):

``````test[5127:207] foo is: 0.124979
test[5127:207] ifoo is: 125, and back to foo is: 0.125000
``````

so that might do what you want.

luck.

Share:
11,636

Author by

### lifemoveson

Software Developer writing code for mobile devices i.e. iphone and Android using Objective C/Swift 3, Android Java.

Updated on June 04, 2022

• lifemoveson over 1 year

Possible Duplicate:
NSNumberFormatter for rounding up float values

Currently, I calculate the scaling factor by using :

``````CGFloat scale = CGContextGetCTM(context).a;
NSLog(@"SCALE : %f", scale);
``````

I receive a floating point value as : 0.124979, 0.249958, 0.499917. How can I use roundf to get it convert to 0.125, 0.250, 0.500 respectively.

• lifemoveson over 12 years
Thanks. But how can I convert the rounding in this : CGFloat scale = CGContextGetCTM(context).a;
• Aravindhan over 12 years
try NSLog(@"SCALE: %.3fg",scale);
• Aravindhan over 12 years
I dont have mac now.. so I cant able to give the answer exactly :(
• lifemoveson over 12 years
when I do NSLog(@"SCALE : %.3f", scale); it gives me correct output. But I want to use scale for future and not only to display it.
• Aravindhan over 12 years
@lifemoveson: If you dont get the desired output means dont mark this as accepted answer. Then only you can able to get the correct answer from the other users.
• Aravindhan over 12 years