PDA

View Full Version : the inverse of print(@"%.3e",3.1415926535)




MrFusion
Mar 15, 2008, 12:27 PM
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.

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);
};



aross99
Mar 15, 2008, 02:05 PM
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?

MrFusion
Mar 15, 2008, 02:38 PM
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?

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.

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);