Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting of a Double [duplicate]

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!

like image 607
zbrox Avatar asked Jun 04 '14 20:06

zbrox


People also ask

What is the format string for double?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you format a double to two decimal places?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places. However, we can't configure the rounding mode in String.


2 Answers

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) 
like image 190
Cezary Wojcik Avatar answered Sep 20 '22 13:09

Cezary Wojcik


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

let str = String(format: "%.2f", 1.23) 
like image 22
hallski Avatar answered Sep 19 '22 13:09

hallski