Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a CGFloat from a NSString?

In my current app, I have an equation that typically solves to a pretty long amount of decimal numbers, i.e: 0.12345 or .123 . But the way that I need this to work is to only show say 1 or 2 decimal numbers, so that would essentially produce 0.12 or 0.1 based on the values I mentioned.

In order to do this, I have done the following: Taken my CGFloat to a NSString:

CGFloat eX1 = 0.12345
NSLog(@" eX1 = %f", eX1);  //This of course , prints out 0.12345

NSNumberFormatter *XFormatter = [[NSNumberFormatter alloc] init];
Xformatter.numberStyle=NSNumberFormatterDecimalStyle;
Xformatter.maximumFractionDigits=1;


NSString *eX1F = [formatter stringFromNumber:@(eX1)]; 
NSLog (@"eX1F = %@",eX1F);  //This prints out 0.1

But my problem is that I need to keep working with this as a CGFloat after it has been formatted, I have tried taken the string back to a number by doing: numberFromString but the problem is that only works with a NSNumber.

What can I do to format my CGFloat and keep working with it as a CGFloat and not a NSString or NSNumber?

Update I have tried:

float backToFloat = [myNumber floatValue];

but the result is number unformatted : 0.10000 I need those extra 0s out

like image 363
vzm Avatar asked Feb 26 '26 07:02

vzm


2 Answers

To convert NSString to a CGFloat you can use floatValue:

CGFloat *eX1rounded = [eX1F floatValue];

But you can round eX1 to eX1rounded directly without using a number formatter, for example:

CFGloat *eX1rounded = roundf(eX1F * 10.0f)/10.0f;

In any case, you should keep in mind that numbers like 0.1 cannot be represented exactly as a binary floating point number.

like image 53
Martin R Avatar answered Feb 28 '26 21:02

Martin R


Use stringWithFormat: to round and convert to a string for display purposes:

NSString* str = [NSString stringWithFormat:@"%0.2f", eX1];

You can do the same thing in NSLog, the %0.2f says you want 2 decimal places.

NSLog(@" eX1 =%0.2f", eX1);   // this prints "0.12"
like image 41
progrmr Avatar answered Feb 28 '26 21:02

progrmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!