# the inverse of print(@"%.3e",3.1415926535)

Discussion in 'Mac Programming' started by MrFusion, Mar 15, 2008.

1. ### MrFusion macrumors 6502a

Joined:
Jun 8, 2005
Location:
West-Europe
#1
If I have a number I can use printf (%,i,g,f,e,...) to format it in the way I want to display it onscreen. But how do to the reverse? Suppose the user give me a number, how can I get the format out of it? I use that number to generate another number, but I want to return it to the user in the same format as his number (e.i. the same precision).

This is more of an algorithm question than xCode/cocoa question, I know. Does anyone perhaps knows a good site with basic computer science algorithms, where such questions are more appropriate?

Thanks.
---
This is what I tried, but which doesn't work for some reason.
Code:
```float userInput = 3.1415;
float integral;
float frac = modff(interval,& integral);
int a=0;
while (frac != 0.0) {
frac = frac*10;
a++;
frac = modff(frac,&integral);
};
```

2. ### aross99 macrumors 68000

Joined:
Dec 17, 2006
Location:
East Lansing, MI
#2
How about accepting the number as a string, and then looking for the decimal point, and computing the number of characters to the left and right of the decimal point? Use something like atoi() to convert the string to the numeric value...

Would that work?

3. ### MrFusion thread starter macrumors 6502a

Joined:
Jun 8, 2005
Location:
West-Europe
#3
It does. Took me maybe 5 minutes to cobble this together (which assumes that there is a decimal place ".").
Maybe I should upgrade my programming level from noob to amateur, when asking questions
But maybe it can be done more efficiently with C functions.
Code:
```	NSNumber *nbr = [NSNumber numberWithFloat:3.141592];//given number from somewhere
NSString *str = [nbr stringValue];//convert to string
NSLog(@"%@",str);//how does it look like on the screen
NSArray *components = [str componentsSeparatedByString:@"."];// separate
int left=[[components objectAtIndex:0] length],right=[[components objectAtIndex:1] length]; //count
int total=left+right;//don't count the decimal place.
NSLog(@"%i = %i.%i",total, left, right);
```