Swift example

How to convert a string to an int in Swift

10 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use Int(text). It returns an Int? that is nil when the text isn't a whole number, so unwrap it: if let n = Int(text) { … }, or Int(text) ?? 0 for a default. The other way round, String(n) or "\(n)" turns an Int into text. Double(text) parses decimals, Int(x) converts a Double by dropping the fraction, and Int(x.rounded()) rounds it to the nearest whole number.

Swift has no parseInt or atoi. Every number type has an initializer that takes a string, Int(_:), Double(_:), Int8(_:) and so on, and each returns an optional, so a failed parse is nil rather than an exception or a silent zero. The sections below cover Int(_:) and what it rejects, trimming, other bases and integer sizes, the opposite direction from Int to String, parsing a Double, converting a Double or Float to an Int with or without rounding, and text written with separators like "1,234", then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Int(_:): a String to an IntRecommended

Int(_:) takes a String (or a Substring) and returns an Int?: the number, or nil when the whole text isn't a valid whole number. It needs no import. Because the result is optional, the compiler makes you handle the failure before you can do arithmetic with it: bind it with if let or guard let, or supply a default with ??. If optionals are new to you, see how to unwrap an optional.

int_init.swift
// Int(_:) returns Int?: nil when the text is not a whole number
let text = "42"
if let n = Int(text) {
    print("n + 1 =", n + 1)
}

// A default for input that does not parse
let count = Int("many") ?? 0
print("count:", count)

// What parses and what does not
let inputs = ["-17", "+5", "007", " 5", "3.0", "", "42abc",
              "99999999999999999999"]
for input in inputs {
    if let value = Int(input) {
        print("\"\(input)\" -> \(value)")
    } else {
        print("\"\(input)\" -> nil")
    }
}

// In a function, guard let keeps the value for the rest of it
func doubled(_ text: String) -> String {
    guard let n = Int(text) else {
        return "\(text) is not a whole number"
    }
    return "\(text) doubled is \(n * 2)"
}
print(doubled("21"))
print(doubled("twenty"))

Output

"42" gives n + 1 = 43, and "many" falls back to count: 0. The loop shows how strict the parser is: a sign is fine (+5 gives 5) and leading zeros are ignored (007 gives 7), but a leading space, a decimal point, the empty string, trailing letters and a number bigger than Int.max all give nil. It never returns part of a number, so "42abc" is nil, not 42. Avoid Int(text)! on input you don't control: when the text isn't a number, it stops the program with Fatal error: Unexpectedly found nil while unwrapping an Optional value.

2Whitespace, other bases and integer sizes

Text from a file, a form or readLine() often carries a space or a newline, and Int(_:) rejects both. Trim first with trimmingCharacters(in:), which comes from Foundation. For hex, binary or any base from 2 to 36, pass radix:; the text must not start with 0x, so drop the prefix first. Every integer type, from Int8 to UInt64, has the same initializer and returns nil when the value doesn't fit that type. To parse a list, compactMap converts each piece and drops the ones that fail.

trim_radix.swift
import Foundation

// Int(_:) does not skip spaces or newlines: trim them first
let line = "  42\n"
print(Int(line) as Any)
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
print(Int(trimmed) as Any)

// Other bases: radix 2 to 36, no 0x prefix
print(Int("ff", radix: 16) as Any)
print(Int("1010", radix: 2) as Any)
print(Int("0x1F", radix: 16) as Any)
let hex = "0x1F"
print(Int(hex.dropFirst(2), radix: 16) as Any)

// Every integer type has the same initializer and checks its own range
print(Int8("200") as Any)
print(UInt("-1") as Any)
print(Int64("9000000000") as Any)

// Parse a list and drop what doesn't parse
let fields = "8,abc,15, 4".split(separator: ",")
let numbers = fields.compactMap { Int($0) }
print(numbers)
let all = fields.compactMap {
    Int($0.trimmingCharacters(in: .whitespaces))
}
print(all)

Output

" 42\n" is nil until it is trimmed, then Optional(42); the as Any only silences the warning Swift gives when you print an optional. Hex ff is 255 and binary 1010 is 10. "0x1F" is nil with radix 16 until dropFirst(2) removes the prefix, which gives 31. Int8("200") is nil because an Int8 stops at 127, and UInt("-1") is nil because it can't hold a negative number. In the list, the first compactMap silently drops " 4" as well as abc ([8, 15]); trimming each piece keeps it ([8, 15, 4]).

3An Int to a String

This direction can't fail, so there is nothing to unwrap. String(n) is the explicit conversion, string interpolation "\(n)" is what you use when the number sits inside other text, and n.description gives the same result. String(_:radix:) writes other bases. An Int? needs unwrapping first: interpolated as it is, "value: \(maybe)" prints value: Optional(7) and the compiler warns that string interpolation produces a debug description for an optional value.

int_to_string.swift
let n = 42

// Three ways to get "42"
let a = String(n)
let b = "\(n)"
let c = n.description
print(a, b, c, a == b && b == c)

// Interpolation builds the text around the number
let total = 1299
print("Total: \(total) items")

// Other bases
print(String(255, radix: 16))
print(String(255, radix: 16, uppercase: true))
print(String(5, radix: 2))

// An optional Int: unwrap first, or map
let maybe: Int? = Int("7")
let none: Int? = nil
print(maybe.map(String.init) ?? "none")
print(none.map(String.init) ?? "none")

// Doubles and Floats work the same way
print(String(3.14), "\(2.5)", String(Float(0.1)))
print(String(0.1 + 0.2))

Output

All three give 42 and compare equal (true). String(255, radix: 16) is ff, FF with uppercase: true, and 5 in binary is 101. map(String.init) converts the value inside the optional, and ?? "none" covers nil. A Double converts the same way and prints the shortest text that reads back as the same value: 3.14, 0.1 for the Float, and 0.30000000000000004 for 0.1 + 0.2, because that sum isn't exactly 0.3 in binary floating point.

4A String to a Double

Double(_:) and Float(_:) work like Int(_:): they return an optional and reject anything that isn't a complete number. They accept a sign, a leading . and exponents like 1e3. They always use a dot for decimals, whatever the device's language, so "3,5" fails; section 6 covers text written with commas. They also accept a few spellings you may not want from a user: inf, nan and hexadecimal floats.

string_to_double.swift
// Double(_:) returns Double? just like Int(_:)
if let price = Double("19.99") {
    print(price * 2)
}

// It reads the formats Swift itself writes
let inputs = ["3.14", "-2.5", ".5", "1e3", "+7", "3,5", " 3", "abc"]
for input in inputs {
    print("\"\(input)\" ->", Double(input) as Any)
}

// Watch out: these parse too
for input in ["inf", "nan", "1e400", "0x1p4"] {
    print("\"\(input)\" ->", Double(input) as Any)
}

// Keep only ordinary numbers
func parseFinite(_ text: String) -> Double? {
    guard let value = Double(text), value.isFinite else {
        return nil
    }
    return value
}
print(parseFinite("2.75") as Any, parseFinite("inf") as Any)

// Float(_:) works the same with less precision
print(Float("3.14") as Any, Float("1e40") as Any)

Output

19.99 doubled prints 39.98, "1e3" is 1000.0 and "+7" is 7.0, while "3,5" and " 3" are nil. The second loop is the gotcha: "inf" and "nan" parse to infinity and not-a-number, "1e400", too big for a Double, becomes inf here rather than nil, and "0x1p4" is a hex float worth 16.0. parseFinite checks isFinite to refuse the first three and prints Optional(2.75) nil. Float follows the same rules with about 7 significant digits and a smaller range, so 1e40 is already inf.

5A Double or Float to an Int: truncate or round

Int(x) converts a Double or Float by dropping everything after the decimal point, so it rounds toward zero: 2.7 becomes 2 and -2.7 becomes -2. For the nearest whole number, round first with rounded(), which sends halves away from zero, then convert. rounded(_:) takes a rule: .down, .up, .towardZero or .toNearestOrEven (banker's rounding). On Linux, as on this page, rounded() needs import Foundation (or Glibc): without it the program fails to link with undefined reference to 'round'. One more catch: Int(x) crashes when x is NaN, infinite or outside the Int range, and Int(exactly:) is the checked version.

double_to_int.swift
import Foundation

// Int(_:) on a Double drops the fraction: it truncates toward zero
print(Int(2.7), Int(-2.7), Int(9.99))
let f: Float = 9.99
print(Int(f))

// Round first for the nearest Int (halves go away from zero)
print(Int(2.7.rounded()), Int((-2.7).rounded()), Int(2.5.rounded()))

// Other rounding rules
let x = 2.5
print(x.rounded(.down), x.rounded(.up), x.rounded(.towardZero))
print(x.rounded(.toNearestOrEven), (-x).rounded(.down))

// Int(exactly:) is nil unless the value is already a whole number
let whole = 3.0
let half = 3.5
print(Int(exactly: whole) as Any, Int(exactly: half) as Any)

// Int(_:) traps on NaN, infinity and values beyond Int.max,
// so check first when the Double comes from outside
func toInt(_ value: Double) -> Int? {
    Int(exactly: value.rounded())
}
let values = [19.6, -0.4, 3e20, Double.nan, Double.infinity]
for value in values {
    print(value, "->", toInt(value) as Any)
}

// From text: parse a Double, then round it
let rating = Double("4.6").map { Int($0.rounded()) }
print(rating as Any)

Output

The first line is 2 -2 9: the fraction is cut off, even from 9.99, and the Float gives 9 as well. After rounded(), 2.7, -2.7 and 2.5 become 3 -3 3. For 2.5, the rules print 2.0 3.0 2.0 for down, up and toward zero, and 2.0 for to-nearest-or-even; -2.5 rounded down is -3.0. Int(exactly:) gives Optional(3) for 3.0 and nil for 3.5, and after rounded() it turns NaN, infinity and 3e+20 into nil instead of a crash. Without the check, Int(big) with big = 3e20 stops the program with Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max, and NaN ends it with Fatal error: Double value cannot be converted to Int because it is either infinite or NaN. With a literal, Int(3e20) doesn't even compile: error: invalid conversion: '3e20' overflows 'Int'. To round to a number of decimal places instead, see rounding to 2 decimal places.

6Numbers with separators, like "1,234"

Int(_:) and Double(_:) read the format Swift writes, not the one people type: no thousands separators, and always a dot for decimals. For text written for humans, use NumberFormatter from Foundation with numberStyle = .decimal and the locale the text was written in. Set the locale yourself: the default, Locale.current, follows the user's device, so the same string can parse differently on two phones. number(from:) returns an NSNumber?; read intValue or doubleValue from it.

number_formatter.swift
import Foundation

// "1,234" is a number to a person, but not to Int(_:) or Double(_:)
print(Int("1,234") as Any, Double("1,234.5") as Any)

// NumberFormatter reads it the way a given locale writes it
let us = NumberFormatter()
us.locale = Locale(identifier: "en_US")
us.numberStyle = .decimal
print(us.number(from: "1,234")?.intValue as Any)
print(us.number(from: "1,234.5")?.doubleValue as Any)

let german = NumberFormatter()
german.locale = Locale(identifier: "de_DE")
german.numberStyle = .decimal
print(german.number(from: "1.234,5")?.doubleValue as Any)

// Gotcha on Linux here: trailing junk is dropped, not rejected
print(us.number(from: "12abc")?.intValue as Any)

// Strict: remove the locale's grouping separator, then use Int(_:)
func parseGroupedInt(_ text: String, locale: Locale) -> Int? {
    let separator = locale.groupingSeparator ?? ","
    return Int(text.replacingOccurrences(of: separator, with: ""))
}
let enUS = Locale(identifier: "en_US")
print(parseGroupedInt("1,234,567", locale: enUS) as Any)
print(parseGroupedInt("12abc", locale: enUS) as Any)
print(parseGroupedInt("1.234", locale: Locale(identifier: "de_DE")) as Any)

// The same formatter writes numbers back out
print(us.string(from: 1234567) ?? "")
print(german.string(from: 1234.5) ?? "")

Output

Plain Int and Double give nil nil. The en_US formatter reads 1,234 as 1234 and 1,234.5 as 1234.5, and the German one reads 1.234,5, where the dot groups digits and the comma marks decimals, as the same 1234.5. On Linux here the formatter is lenient, though: "12abc" comes back as Optional(12), and intValue quietly cuts off a fraction ("1,234.7" gives 1234). When you need a whole number and nothing else, parseGroupedInt removes the locale's groupingSeparator and hands the rest to Int(_:), which stays strict: Optional(1234567), nil for 12abc, and Optional(1234) for the German 1.234. The same formatters also write numbers: 1,234,567 and 1.234,5.

7Which should you use?

MethodGivesOn bad inputBest for
Int(text)Int?nilString to Int, most code
Int(text, radix: 16)Int?nilHex, binary and other bases
String(n), "\(n)"StringCannot failInt to String
Double(text)Double?nil, but accepts inf and nanString to Double; check isFinite
Int(x)IntCrashes on NaN or overflowDouble to Int, dropping the fraction
Int(x.rounded())IntCrashes on NaN or overflowNearest whole number
Int(exactly: x.rounded())Int?nilDoubles from outside your code
NumberFormatterNSNumber?nil, but reads "12abc" as 12 hereText with separators like "1,234"

Frequently asked questions

How do I convert an Int to a String in Swift?

Use String(n), or string interpolation "\(n)" when the number is part of a longer text; n.description gives the same result. All three turn 42 into "42". For another base, String(255, radix: 16) gives "ff". If the value is an Int?, unwrap it first or write value.map(String.init) ?? "none", otherwise you get "Optional(7)".

Why does Int("3.0") or Int(" 5") return nil?

Int(_:) only accepts the whole text as a whole number: an optional sign followed by digits. A decimal point, a space, a newline or any other character makes it return nil. Trim the input with trimmingCharacters(in: .whitespacesAndNewlines) first, and for text that may hold a decimal, parse it with Double(_:) and convert: Double("3.0").map { Int($0) } gives Optional(3).

How do I round a Double to the nearest Int in Swift?

Round, then convert: Int(x.rounded()). rounded() sends halves away from zero, so 2.5 gives 3 and -2.5 gives -3; pass .toNearestOrEven for banker's rounding, .down or .up for floor and ceiling. Foundation's round(x) does the same as x.rounded(). Plain Int(x) does not round: it drops the fraction, so Int(2.7) is 2.

What happens when a Double is too big for an Int?

Int(x) crashes. Here it stops with "Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max", and NaN or infinity give "because it is either infinite or NaN". Use Int(exactly: x.rounded()) on values you did not compute yourself: it returns nil for all three cases.

Is it safe to write Int(text)!?

Only for text you wrote yourself, such as a constant. For anything from a user, a file or the network, ! crashes on bad input with "Fatal error: Unexpectedly found nil while unwrapping an Optional value". Use if let n = Int(text), guard let, or Int(text) ?? 0 instead.

How do I convert a Character to an Int?

Use wholeNumberValue: Character("7").wholeNumberValue is Optional(7) and Character("x").wholeNumberValue is nil. It also reads digits from other scripts, so the Arabic-Indic digit "٣" gives 3, while Int("٣") is nil because Int(_:) accepts only ASCII digits. Int(String(ch)) works too for ASCII digits.

Should I use Double or Decimal for money?

Decimal. A Double stores binary fractions, so 0.1 + 0.2 prints 0.30000000000000004. Decimal(string: "0.1") returns a Decimal? that holds 0.1 exactly, and adding Decimal(string: "0.2") to it prints 0.3. It comes from Foundation.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground