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?
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" .
Just convert the string to an int and then back to a string again. It will remove the leading zeros.
zero should never be used as an extension on a primitive such as Int or Double . Instead, use the raw 0 value.
By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.
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))!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With