William Falcon
William Falcon

Reputation: 9813

drop decimals in this method

I have a statement that shows 50.02%

How can I drop the decimals and show 50%?

Sorry this is so basic, pretty new to xcode.

Thank you in advance.

 -(void)updatePercent{

percent.text = [NSString stringWithFormat:@"%.2f%@", 100.0f, @"%"];

}

Upvotes: 0

Views: 71

Answers (2)

sergio
sergio

Reputation: 69027

Use this:

percent.text = [NSString stringWithFormat:@"%.0f%%", 100.0f];

Also note the use of %% to print a single %.

Upvotes: 2

MJN
MJN

Reputation: 10808

When printing floats, you can control how many decimals places are printed out by using numbers between the % and the f in the %f format statement.

The number on the right of the decimal tells how many decimal places should be printed. The number on the left of the decimal tells at least how many total places should be printed (including the decimal and all digits). If the number on the left is prefixed by a zero, the resulting string will have zeros appended to the left.

float myNum = 32.142;

// without declaring total digits
[NSString stringWithFormat:@"%.0f"]  // 32
[NSString stringWithFormat:@"%.2f"]  // 32.14
[NSString stringWithFormat:@"%.5f"]  // 32.14200

// put a zero in front of the left digit
[NSString stringWithFormat:@"%010.0f"] // 0000000032
[NSString stringWithFormat:@"%010.2%"] // 0000032.14

// without the zero prefix (leading whitespace)
[NSString stringWithFormat:@"%10.2f"]  //      32.14

Upvotes: 1

Related Questions