Search code examples
swiftnumber-formatting

Always format String or Number to XX.XX


I am trying to format any number to XX.XX

I have tried as below

import Foundation

let b = 2.1
var str = String(format:"%.02f", b)
print(str) // 2.10
//Needed output as 02.10

But I need the output as 02.10

If the number is 0.8 then it should be 00.80

Please suggest the solution.


Solution

  • The format you are looking for would be "%05.2f", but you can use a the NumberFormatter:

    import Foundation
    
    let formatter = NumberFormatter()
    formatter.minimumFractionDigits = 2
    formatter.minimumIntegerDigits = 2
    

    Then:

    formatter.string(from: 0.8)! // Will be 00.80
    formatter.string(from: 2.1)! // Will be 02.10