Leading zeros for float in Swift

Below is some float value:

5.3 23.67 0.23 

and I want them to be

 05.30 23.67 00.23 

Using String(format: "%.2f", floatVar) can do 2 digits after the decimal point, but cannot add a zero in front of it.

I also tried String(format: "%04.2f", floatVar) as suggested here , but it just displays the same as %.2f

Is there a clean way to do this in standard Swift libraries?

+5
source share
2 answers

Try the following:

 String(format: "%05.2f", floatChar) 

From this documentation : 0 means it has a leading zero. 5 - minimum width, including the dot symbol.

+14
source

Or I can try a more powerful NumberFormatter api

 let numberFormatter = NumberFormatter() // more settings numberFormatter.minimumIntegerDigits = 2 
0
source

Source: https://habr.com/ru/post/1234902/


All Articles