tags:

views:

4169

answers:

4

as title, i have a value 25.00 i use float as a variable but when i print it on screen it is 25.0000000 how can i set the decimal number in two only

+10  A: 

It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

E.g;

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0's.

E.g.

%f = 25.000000
%.2f = 25
%.02f = 25.00
Andrew Grant
A: 

IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:

printf("%.02f", your_float_var);

OTOH, if what you want is to store that value on a char array you could use:

sprintf(your_char_ptr, "%.02f", your_float_var);
Pablo Santa Cruz
A: 

in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display e.g 0.02f will print 25.00 0.002f will print 25.000

shaunak
A: 

You can also try using NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

You may need to also set the negative format, but I think it's smart enough to figure it out.

Rick