Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MrFusion

macrumors 6502a
Original poster
Jun 8, 2005
613
0
West-Europe
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);		
};
 

aross99

macrumors 68000
Dec 17, 2006
1,541
1
East Lansing, MI
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

macrumors 6502a
Original poster
Jun 8, 2005
613
0
West-Europe
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.
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);
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.