0

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.

rkb
  • 10,933
  • 22
  • 76
  • 103

2 Answers2

1

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
  • 35,429
  • 19
  • 126
  • 178
  • 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 Aug 18 '09 at 23:05
  • 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 Aug 18 '09 at 23:55
0

I got the solution,

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

rkb
  • 10,933
  • 22
  • 76
  • 103