Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading and trailing zeroes to a string/label in swift

Tags:

string

swift

In swift I know how to set the number of digits after the decimal point when converting a double to a string:

String(format: "%0.2f", someDouble)

Similarly I know how to set the number of digits before the decimal point:

String(format: "%02d", someDouble)

But how can I do both?

I want the string to always have a 00.00 format.

Thanks

like image 722
ZackBoi Avatar asked Dec 05 '22 10:12

ZackBoi


1 Answers

You simply combine the two:

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

The 0 means fill with leading zeros as needed.
The 5 means you want the final output to be at least 5 characters, include the decimal point.
The .2 means you want two decimal places.

If this is a number you are showing to a user then you should probably use NumberFormatter so the decimal is properly formatted for the user's locale.

like image 125
rmaddy Avatar answered Jan 01 '23 06:01

rmaddy