Swift
String Manipulation
Data Conversion
Float Conversion
Programming Tutorial

Convert String to Float in Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting a string to a floating-point number in Swift is usually straightforward, but the details matter once user input, locale rules, or invalid data enter the picture. Swift gives you safe initializers for Float and Double, and both return optionals so conversion failures are explicit. The right solution depends on whether you control the string format or need to parse human-entered numbers.

Use the Built-In Initializers

If the string already uses a standard decimal format, Swift can parse it directly.

swift
1let text = "3.14159"
2
3if let value = Float(text) {
4    print(value)
5} else {
6    print("Invalid float")
7}

You can do the same with Double:

swift
1let text = "3.14159"
2
3if let value = Double(text) {
4    print(value)
5} else {
6    print("Invalid double")
7}

The important part is that the result is optional. If parsing fails, you get nil instead of a silent wrong value.

Prefer Double Unless You Need Float

Swift supports both Float and Double, but Double is usually the better default because it has more precision.

Use Float when:

  • an API specifically expects Float
  • memory layout matters in numeric arrays
  • you are working with frameworks that use Float heavily

For general app code, Double is the more common choice.

swift
let amountText = "12.75"
let amount = Double(amountText)
print(amount as Any)

If the ultimate destination type is Float, you can convert after successful parsing.

Trim Whitespace Before Parsing

Strings from text fields, files, or network payloads often contain leading or trailing spaces. Trimming them makes parsing more reliable.

swift
1let rawText = "  42.5 \n"
2let cleaned = rawText.trimmingCharacters(in: .whitespacesAndNewlines)
3
4if let value = Double(cleaned) {
5    print(value)
6}

This is a small step, but it removes a common source of avoidable parsing failures.

Handle Invalid Input Safely

Do not force-unwrap a parsed number unless the input is guaranteed by your own code. User input and external data are not guaranteed.

Unsafe:

swift
let value = Float("abc")!

Safe:

swift
1let text = "abc"
2
3guard let value = Float(text) else {
4    print("Please enter a valid number.")
5    exit(0)
6}
7
8print(value)

The safe version makes the failure path explicit and prevents runtime crashes.

Use NumberFormatter for Locale-Aware Parsing

The simple initializers expect a predictable machine-style number format, usually with . as the decimal separator. Human-entered values may use locale-specific separators instead.

For example, some locales write 12,5 instead of 12.5. NumberFormatter is the right tool for that.

swift
1import Foundation
2
3let formatter = NumberFormatter()
4formatter.locale = Locale(identifier: "fr_FR")
5formatter.numberStyle = .decimal
6
7let text = "12,5"
8
9if let number = formatter.number(from: text) {
10    print(number.doubleValue)
11} else {
12    print("Invalid localized number")
13}

If your app accepts user-facing numeric input, locale-aware parsing is often more correct than calling Double(text) directly.

Converting From Text Fields

A very common case is converting input from UITextField or TextField content.

swift
1let textFieldValue = "99.95"
2
3if let price = Double(textFieldValue) {
4    print("Parsed price:", price)
5} else {
6    print("Could not parse price")
7}

In real apps, combine this with validation and user feedback rather than failing silently.

Common Pitfalls

The biggest mistake is force-unwrapping the conversion result. A single invalid string then becomes a crash instead of a validation error.

Another issue is choosing Float automatically when Double would be a better default. Unless an API requires Float, Double usually gives you fewer precision surprises.

Locale is another subtle problem. A string that looks correct to the user may still fail with Double(text) if the decimal separator does not match the machine-oriented format expected by the initializer.

Finally, remember to trim whitespace when parsing raw input. Many “mysterious” failures are just unclean strings.

Summary

  • Use Float(text) or Double(text) for standard numeric strings.
  • Treat the result as optional and handle failure explicitly.
  • Prefer Double unless you specifically need Float.
  • Trim whitespace before parsing user or external input.
  • Use NumberFormatter when the input format depends on locale rules.

Course illustration
Course illustration

All Rights Reserved.