String formatting of a Double
Solution 1
There's no way to do this using String
interpolation.
You can find a good discussion about this on this Apple Dev Forum post.
You can use NSNumberFormatter
or NSDateFormatter
to format the output.
Alternatively, to use printf
-like syntax, you can still use NSString
:
var str = NSString(format: "Hello, world %.2f", 42.12312312313)
Solution 2
Unsure if there is a pure Swift-way but you can always use NSStrings +stringWithFormat:
:
let str = String(format: "%.2f", 1.23)
Related videos on Youtube
zbrox
Creating some really fun stuff at The Techno Creatives, using mostly Swift, Qt/QML, and TypeScript (Node.js, React). If not doing that probably talking a lot, wondering if I can become a stand up comic, learning Swedish.
Updated on July 09, 2022Comments
-
zbrox almost 2 years
I can't seem to find a way to format a Double limiting the precision to just a couple of positions after the decimal point when presenting that in a label. Maybe I'm missing something major, but I couldn't find anything in the official documentation.
Thanks in advance for the help!
-
Rob about 9 yearsBy the way, I would prefer
NSNumberFormatter
, which honors the device'slocale
. Thuslet formatter = NSNumberFormatter()
, setminimumFractionDigits
andmaximumFractionDigits
to however many digits you want, and then you can dolet string = formatter.stringFromNumber(3.1415)
.
-
-
NRitH almost 10 yearsFor something as simple as this example, this is a perfectly good solution.
-
Sébastien REMY almost 8 yearsYou may use String not NSString : let str = String(format: "%.2f", 1.23)
-
RonLugge over 6 yearsFYI, your link appears to have experienced linkrot.
-
uplearned.com over 4 yearsSwift5 String(format: "%.2f", arguments: [count])