Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading zeros for float in Swift

Here are 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 make 2 digit following the decimal point but cannot add zero before it.

I've also tried String(format: "%04.2f", floatVar) as suggest here but it just display same as %.2f

Is there a clean way of doing this within the Swift standard libraries?

like image 777
He Yifei 何一非 Avatar asked Oct 31 '15 02:10

He Yifei 何一非


People also ask

How do I add a zero in front of a number in Swift?

By the way: If I just wanted a single zero in front of my number I'd chose println("0\(myInt)") over your suggestion. That would use Swift native String class instead going through NSString formatting. String(format: "%03d", myInt) will give you "000", "001", ... , "099", "100" .

How do I remove leading zeros in Swift?

Just convert the string to an int and then back to a string again. It will remove the leading zeros.

Is 0 an int in Swift?

zero should never be used as an extension on a primitive such as Int or Double . Instead, use the raw 0 value.

How do you round a double to two decimal places in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.


1 Answers

If you want a quick and dirty solution:

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

From this documentation: 0 means pad it with leading zero. 5 is the minimum width, including the dot character.


The longer answer is that some locales use comma as the decimal separator. If you want to match the user's locale, use NumberFormatter:

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.minimumIntegerDigits = 2

formatter.string(from: NSNumber(value: floatChar))!
like image 172
Code Different Avatar answered Sep 20 '22 20:09

Code Different