How to round of CGFloat value
Solution 1
Try this........
NSLog(@"SCALE : %.3f", scale);
NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];
Stolen from Previous SO answer
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.
Related videos on Youtube
lifemoveson
Software Developer writing code for mobile devices i.e. iphone and Android using Objective C/Swift 3, Android Java.
Updated on June 04, 2022Comments
-
lifemoveson almost 2 years
Possible Duplicate:
NSNumberFormatter for rounding up float valuesCurrently, 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 almost 13 yearsThanks. But how can I convert the rounding in this : CGFloat scale = CGContextGetCTM(context).a;
-
Aravindhan almost 13 yearstry NSLog(@"SCALE: %.3fg",scale);
-
Aravindhan almost 13 yearsI dont have mac now.. so I cant able to give the answer exactly :(
-
lifemoveson almost 13 yearswhen 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 almost 13 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 almost 13 yearssee the updated answer now......
-
lifemoveson almost 13 yearsThanks. Actually I thought accepted answer mean if its the correct answer. I have changed the code again.
-
Dad almost 13 yearscorrect means it answered the question you were asking, did it?