To show a number with 2 decimals, format it: String(format: "%.2f", x) turns 3.14159 into "3.14", and x.formatted(.number.precision(.fractionLength(2))) does the same with the user's locale. To round the Double itself, write (x * 100).rounded() / 100. For money, use Decimal, not Double.
"Round to 2 decimal places" means two different things. Most of the time you want to display a number with two digits after the point, and that is a formatting job: the result is a String. Sometimes you want the value rounded for further math, and then a Double can only get you close, because it stores numbers in binary and 1.005 is really a little less than 1.005. The sections below cover formatting with String(format:) and formatted(), rounding the value, the rounding rules, Decimal for exact cents, leading zeros and padding, and NumberFormatter, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1Format it for display: String(format:) and formatted()Recommended
String(format: "%.2f", x) uses printf-style format specifiers: %.2f means a floating-point number with exactly 2 digits after the point, padded with zeros if needed. It needs import Foundation. The newer formatted() API (FormatStyle) does the same with .precision(.fractionLength(2)) and also adds grouping separators and the right decimal mark for a locale. By default it follows the user's device settings, so the examples pin en_US to print the same everywhere. Pass a range, .fractionLength(0...2), to show at most two digits and drop trailing zeros.
import Foundation let price = 3.14159 let en = Locale(identifier: "en_US") // printf-style: always exactly 2 digits after the point print(String(format: "%.2f", price)) print(String(format: "%.2f", 2.5)) // FormatStyle: the same, plus grouping and a locale let twoPlaces = FloatingPointFormatStyle<Double>(locale: en) .precision(.fractionLength(2)) print(price.formatted(twoPlaces)) print(1234567.891.formatted(twoPlaces)) // The same number for a German reader let de = Locale(identifier: "de_DE") print(price.formatted(.number.precision(.fractionLength(2)).locale(de))) print(String(format: "%.2f", locale: de, price)) // At most 2 digits: trailing zeros are dropped let upToTwo = FloatingPointFormatStyle<Double>(locale: en) .precision(.fractionLength(0...2)) for x in [3.0, 2.5, 3.14159] { print(x.formatted(upToTwo)) }
Output
Both give 3.14, and 2.5 is padded to 2.50. The format style also groups thousands, 1,234,567.89, which %.2f never does. With a German locale both print 3,14. The range version prints 3, 2.5 and 3.14. Either way you get a String for a label or a log line; the Double itself is unchanged, which is what you want if you keep calculating with it.
2Round the Double itself: (x * 100).rounded() / 100
When the rounded number has to stay a number, multiply by 100, round to a whole number with rounded(), and divide by 100 again. For other places, use a power of ten; the small extension below wraps that up as rounded(toPlaces:) (pow comes with Foundation). This is the top Stack Overflow answer, and it works for cleaning up arithmetic noise. What it can't do is make a Double hold exactly 3.14: binary floating point has no exact form for most decimals, so you get the nearest Double, and the input can already be off before you round.
import Foundation extension Double { // Round to a number of decimal places, half away from zero func rounded(toPlaces places: Int) -> Double { let factor = pow(10.0, Double(places)) return (self * factor).rounded() / factor } } print(3.14159.rounded(toPlaces: 2)) print(1.2345.rounded(toPlaces: 3)) print(2.675.rounded(toPlaces: 2)) // Arithmetic noise goes away let total = 1.1 * 3 print(total, total.rounded(toPlaces: 2)) print(0.1 + 0.2, (0.1 + 0.2).rounded(toPlaces: 2)) // The result is the nearest Double to 3.14, not 3.14 exactly print(String(format: "%.20f", 3.14159.rounded(toPlaces: 2))) // 1.005 is stored as slightly less than 1.005 print(String(format: "%.20f", 1.005)) print(1.005 * 100) print(1.005.rounded(toPlaces: 2))
Output
3.14159 becomes 3.14, and 3.3000000000000003 from 1.1 * 3 becomes 3.3. print shows the shortest text that reads back as the same Double, which is why 3.14 looks exact; %.20f shows what is stored, 3.14000000000000012434. The last three lines are the classic surprise: 1.005 is stored as 1.00499999999999989342, times 100 gives 100.49999999999999, and that rounds down to 1.0. If the digits must be exact, use Decimal (section 4).
3Rounding rules: half up, half even, up and down
rounded() with no argument uses .toNearestOrAwayFromZero: halves go away from zero, the rule taught at school. Pass a FloatingPointRoundingRule for another one: .toNearestOrEven (banker's rounding), .up and .down (toward plus and minus infinity, the same as ceil and floor), .towardZero and .awayFromZero. The values below are halves that binary stores exactly, so only the rule decides. The formatters have their own default, and it is not the same one.
import Foundation func round2(_ x: Double, _ rule: FloatingPointRoundingRule) -> Double { (x * 100).rounded(rule) / 100 } let values = [0.125, 0.375, -0.125, 0.121] let rules: [(String, FloatingPointRoundingRule)] = [ ("toNearestOrAwayFromZero", .toNearestOrAwayFromZero), ("toNearestOrEven", .toNearestOrEven), ("up", .up), ("down", .down), ("towardZero", .towardZero), ] for (name, rule) in rules { print(name, values.map { round2($0, rule) }) } // rounded() with no argument rounds halves away from zero print(2.5.rounded(), 3.5.rounded(), (-2.5).rounded()) // %.2f and %.0f round halves to even print(String(format: "%.2f %.2f", 0.125, 0.375)) print(String(format: "%.0f %.0f", 2.5, 3.5)) // formatted() rounds halves to even too, unless you pick a rule let en = Locale(identifier: "en_US") let style = FloatingPointFormatStyle<Double>(locale: en) .precision(.fractionLength(2)) print(0.125.formatted(style), 1.005.formatted(style)) let halfUp = style.rounded(rule: .toNearestOrAwayFromZero) print(0.125.formatted(halfUp), 1.005.formatted(halfUp))
Output
The four values show each rule: 0.125 goes to 0.13 with the default rule but 0.12 with .toNearestOrEven, while .up turns 0.121 into 0.13. Both %.2f and formatted() round halves to even here: 0.12 0.38, and %.0f prints 2 4 for 2.5 and 3.5. The last line is worth a look: with .rounded(rule: .toNearestOrAwayFromZero) the format style gives 1.01 for 1.005, the answer people expect, because it rounds the decimal text of the number rather than its binary value. String(format: "%.2f", 1.005) prints 1.00.
4Decimal for money and exact digits
Decimal (Foundation) stores base-10 digits, so 19.99 is exactly 19.99 and sums of cents come out right. Build it from a string with Decimal(string:): a Double or a float literal passes through binary first and brings its error along. To round, call NSDecimalRound with a scale (the number of decimal places) and a mode: .plain is half away from zero, .bankers is half to even, and .up and .down go toward plus and minus infinity. There is no rounded method on Decimal here (the compiler says value of type 'Decimal' has no member 'rounded'), so the example wraps the call in a small function.
import Foundation func rounded(_ value: Decimal, scale: Int, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal { var input = value var result = Decimal() NSDecimalRound(&result, &input, scale, mode) return result } // From a string the digits are exact; through a Double they are not let exact = Decimal(string: "1.005")! let viaDouble = Decimal(1.005) let fromLiteral: Decimal = 19.99 print(exact, viaDouble, fromLiteral) print(rounded(exact, scale: 2)) let half = Decimal(string: "0.125")! print(rounded(half, scale: 2, mode: .bankers)) print(rounded(half, scale: 2, mode: .up)) print(rounded(half, scale: 2, mode: .down)) // Exact cents: 3 items, 8.25% tax rounded to the cent let price = Decimal(string: "19.99")! let subtotal = price * 3 let tax = rounded(subtotal * Decimal(string: "0.0825")!, scale: 2) print(subtotal, tax, subtotal + tax) let usd = Decimal.FormatStyle.Currency(code: "USD") .locale(Locale(identifier: "en_US")) print((subtotal + tax).formatted(usd))
Output
Decimal(string: "1.005") prints 1.005, while Decimal(1.005) prints 1.0049999999999997952 and the literal 19.99 becomes 19.98999999999999488: both went through a Double. Rounded with .plain, the exact value gives 1.01. The tax line multiplies and rounds once at the end: 59.97 4.95 64.92, formatted as $64.92. Use Decimal for prices and balances, and keep Double for measurements where the last digit doesn't matter.
5Leading zeros, padding and other format specifiers
The same format strings pad numbers. %03d prints an integer at least 3 characters wide, filled with zeros; %5.1f prints a number with one decimal in a field 5 wide, filled with spaces; a - flag aligns left and a + flag always shows the sign. %@ takes a String, %x prints hex, %e scientific notation, and %% a literal percent sign. With FormatStyle, leading zeros come from .precision(.integerLength(3...)); mind the dots, as the output shows. Without Foundation, pad the string yourself with String(repeating:count:).
import Foundation for n in [7, 42, 1234, -5] { print(String(format: "%03d", n)) } print(String(format: "%02d:%02d:%02d", 9, 5, 0)) // FormatStyle: at least 3 integer digits, no grouping let en = Locale(identifier: "en_US") let threeDigits = IntegerFormatStyle<Int>(locale: en) .precision(.integerLength(3...)) .grouping(.never) print([7, 42, 1234].map { $0.formatted(threeDigits) }) // Exactly 3 digits cuts off the front print(1234.formatted(.number.precision(.integerLength(3)))) // Width, alignment and sign print("[" + String(format: "%5.1f", 3.14159) + "]") print("[" + String(format: "%-8.2f", 2.5) + "]") print(String(format: "%08.3f", -3.14159)) print(String(format: "%+.2f", 2.5)) // Several values in one format string print(String(format: "%@ scored %d (%.1f%%)", "Ada", 42, 87.456)) print(String(format: "%x %X %o %e", 255, 255, 8, 12345.678)) // No Foundation: pad by hand let text = String(42) print(String(repeating: "0", count: max(0, 5 - text.count)) + text)
Output
%03d gives 007 and 042, leaves 1234 alone because the width is a minimum, and counts the sign: -5 becomes -05. .integerLength(3...) pads the same way, but .integerLength(3) without the dots means exactly three digits and turns 1234 into 234. The padded fields print [ 3.1] and [2.50 ], and the mixed format string prints Ada scored 42 (87.5%). Each specifier must match its argument's type; the FAQ below shows what happens when it doesn't.
6NumberFormatter: min and max fraction digits
NumberFormatter is the older, class-based formatter you will see in many answers and in code that targets systems before FormatStyle. Set minimumFractionDigits and maximumFractionDigits to 2 for exactly two decimals, or only the maximum for up to two. Its roundingMode defaults to .halfEven; set .halfUp for school rounding. string(from:) takes an NSNumber and returns an optional String. Create one formatter and reuse it rather than building a new one for every number.
import Foundation let formatter = NumberFormatter() formatter.locale = Locale(identifier: "en_US") formatter.minimumFractionDigits = 2 formatter.maximumFractionDigits = 2 func show(_ x: Double) -> String { formatter.string(from: NSNumber(value: x)) ?? "?" } print(show(3.14159), show(1234.5), show(0.125), show(1.005)) // Half up instead of the default half even formatter.roundingMode = .halfUp print(show(0.125), show(1.005)) // Up to 2 digits formatter.minimumFractionDigits = 0 print(show(3.0), show(2.5), show(3.14159)) // Currency style picks the digits and symbol from the locale let money = NumberFormatter() money.locale = Locale(identifier: "en_US") money.numberStyle = .currency print(money.string(from: NSNumber(value: 1234.5)) ?? "?")
Output
With both limits at 2, 3.14159 prints 3.14 and 1234.5 prints 1234.50 (no grouping without a number style). The default half-even mode gives 0.12 for 0.125; after .halfUp it gives 0.13, and 1.005 gives 1.01, like the format style. On Linux here, also setting numberStyle = .decimal together with minimumFractionDigits made the formatter ignore the maximum and print 3.142; for new code, the formatted() API from section 1 avoids that and needs no setup.
7Which should you use?
| Method | Gives | Halves | Best for |
|---|---|---|---|
| x.formatted(.number.precision(.fractionLength(2))) | String | To even, or a rule you pass | Text a user reads, in their locale |
| String(format: "%.2f", x) | String | To even, on the binary value | Logs, fixed formats, padding with %5.2f |
| (x * 100).rounded() / 100 | Double | Away from zero, or a rule you pass | A rounded value for more math |
| NSDecimalRound on Decimal | Decimal | .plain, .bankers, .up, .down | Money and exact digits |
| NumberFormatter | String? | .halfEven unless set | Existing code, older systems |
| String(format: "%03d", n) | String | n/a | Leading zeros on integers |
Frequently asked questions
How do I round a Double to 2 decimal places in Swift?
For display, format it: String(format: "%.2f", x) or x.formatted(.number.precision(.fractionLength(2))) turn 3.14159 into "3.14". To get a rounded Double back, use (x * 100).rounded() / 100. For money, keep the amount in a Decimal and round it with NSDecimalRound.
Why does (1.005 * 100).rounded() / 100 give 1.0 instead of 1.01?
Because the Double closest to 1.005 is 1.00499999999999989342, so 1.005 * 100 is 100.49999999999999, which rounds down. The number was never exactly 1.005. Use Decimal(string: "1.005") with NSDecimalRound(..., .plain) to get 1.01, or for display formatted(.number.precision(.fractionLength(2)).rounded(rule: .toNearestOrAwayFromZero)), which also prints 1.01.
Why does String(format: "%.2f", 5) print 0.00?
%f expects a floating-point argument and 5 is an Int, so the formatter reads the wrong kind of value and prints 0.00 with no error or warning. Convert first: String(format: "%.2f", Double(n)). The same applies the other way round: use %d for Int and %f for Double and Float.
How do I put a Swift String into a format string?
Use %@: String(format: "%@ scored %d", name, score). %s is for C strings; passed a Swift String it printed an empty string here. String interpolation, "\(name) scored \(score)", is often simpler, and you can mix it with a formatted number: "Total: \(String(format: "%.2f", total))".
How do I add leading zeros to an Int in Swift?
Use String(format: "%03d", n), which pads 7 to "007" and leaves 1234 as "1234", or n.formatted(.number.precision(.integerLength(3...)).grouping(.never)). Note the 3...: .integerLength(3) means exactly three digits and turned 1234 into "234". A negative number counts its sign in the width, so -5 with %03d becomes "-05".
Why does my rounded number print as -0.00?
A small negative value such as -0.004 rounds to negative zero, and %.2f and formatted() both print it as "-0.00". Adding zero after rounding clears the sign: String(format: "%.2f", (x * 100).rounded() / 100 + 0) printed "0.00" for -0.004.
How do I always round up or down to 2 decimal places?
Pass a rule: (x * 100).rounded(.up) / 100 rounds toward plus infinity and (x * 100).rounded(.down) / 100 toward minus infinity, the same as ceil and floor. Use .towardZero to cut off the extra digits. For text, formatted(.number.precision(.fractionLength(2)).rounded(rule: .down)) turned 2.567 into "2.56".