57

I want to get string like "99.99%" from Double,and I used format to get this:

let rate = 99.99999
let str = String(format: "%.2f%", rate)
// output 99.99

And \% is not allowed. So how to add percent sign in string format, please help me!

Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
Lumialxk
  • 6,239
  • 6
  • 24
  • 47

2 Answers2

169

write % twice:

rate = 99.99
let str = String(format: "%.2f%%", rate)
ramzesenok
  • 5,469
  • 4
  • 30
  • 41
Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
16

The % symbol has a special use in a printf statement. How would you place this character as part of the output on the screen?

You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.

Hope it help you :)

Undo
  • 25,519
  • 37
  • 106
  • 129
Darshan
  • 2,272
  • 3
  • 31
  • 43
  • 1
    It works. In my case I'm using a string like "There is a %@ probability" So the solution was: "There is a %@%% probability" – Dasoga Aug 15 '18 at 15:23