String formatting of a Double [duplicate]
Asked Answered
W

2

47

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!

Workmanlike answered 4/6, 2014 at 20:53 Comment(1)
By the way, I would prefer NSNumberFormatter, which honors the device's locale. Thus let formatter = NSNumberFormatter(), set minimumFractionDigits and maximumFractionDigits to however many digits you want, and then you can do let string = formatter.stringFromNumber(3.1415).Shroud
A
47

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)
Anthonyanthophore answered 4/6, 2014 at 20:59 Comment(2)
FYI, your link appears to have experienced linkrot.Realize
Swift5 String(format: "%.2f", arguments: [count])Nomarchy
B
34

Unsure if there is a pure Swift-way but you can always use NSStrings +stringWithFormat::

let str = String(format: "%.2f", 1.23)
Basilicata answered 4/6, 2014 at 20:59 Comment(2)
For something as simple as this example, this is a perfectly good solution.Wichita
You may use String not NSString : let str = String(format: "%.2f", 1.23)Unspotted

© 2022 - 2024 — McMap. All rights reserved.