Avatar ·

Precise formatting of floating-point numbers in Swift: string format specifiers

Hello everyone! I've just started learning Swift and encountered a problem with formatting floating-point numbers. I need to output a value of type Double with a specific number of decimal places, for example, 2 digits. In other languages like C or Java, I used format specifiers such as %.2f, but in Swift this doesn't seem to work directly.

\n\n

Here's what I tried:

\n\n
let pi = 3.1415926535\nlet formatted = String(format: "%.2f", pi)\nprint(formatted) // "3.14" — works!\n
\n\n

But when I tried using String(format:) with other specifiers, for example, %e for scientific notation or %g for automatic format selection, I got strange results. I also need to align