Floating-point number formatting: precision specifier in Swift
Hi everyone! I just started learning Swift and encountered a problem with formatting floating-point numbers. I need to output the value of Pi (3.1415926535) with different precision: for example, 2 decimal places, 3 decimal places, and so on.
In other languages (C, Java), I remember you can use something like `printf("%.2f", pi)` or `String.format("%.2f", pi)`. But in Swift, I can't find the equivalent.
I tried writing like this:
```swift
let pi = 3.1415926535
print("\(pi)") // outputs 3.1415926535
print("\(pi, specifier: "%.2f")") // doesn't work
```
And like this:
```swift
let formatted = String(format: "%.2f", pi) // outputs 3.14
```
This works, but I heard there is a more modern way in Swift. Tell me how to properly format floating-point numbers with a given precision?
No answers yet.
Log in to leave an answer
Blogs