tags:

views:

182

answers:

2

Hello all,

I want to display a number in decimal format only if the number is not an integer. Like if the number is float it must be displayed with one decimal point. But if the number is an integer it must be displayed without a decimal point like its shown in the following link(second part of the code)

http://www.csharp-examples.net/string-format-double/

I am using a string like

NSString *temp =[NSString stringWithFormat:@"0.1f" , 10];

this temp is 10.0 I want it to be 10 but if I am doing as follows

NSString *temp =[NSString stringWithFormat:@"0.1f" , 10.9];

then it must be like 10.9

How to resolve this in iPhone.

+1  A: 

You could check the value of the string against a cast, then format the string accordingly:

float     x = 42.1;  // whatever
long      x_int = x;
bool      is_integer = x_int == x;
NSString* temp = nil;

if (is_integer)
{
    temp = [NSString stringWithFormat:@"%d", x_int];
}
else
{
    temp = [NSString stringWithFormat:@"%0.1f", x];
}
fbrereto
dude I am having the use of the same a lot more places and then my whole code will contain only if, else loop. I need some solution as the string formaters in C++ and %g for printf... See the following link.http://stackoverflow.com/questions/838064/only-show-decimal-point-if-floating-point-component-is-not-00-sprintf-printf
rkb
Using %g works, but keep in mind the precision issue mentioned on the other thread... doesn't sound like it applies to your specific case, however.
fbrereto
A: 

I got the solution,

NSString *temp =[NSString stringWithFormat:@"%g" , 10.9];

rkb