C#
string conversion
float
programming
tutorial

Converting string to float in C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

C# provides three main ways to convert a string to a float: float.Parse() which throws on invalid input, float.TryParse() which returns a boolean indicating success, and Convert.ToSingle() which handles null by returning 0. The key consideration is culture sensitivity — different locales use different decimal separators (. vs ,), so always specify a CultureInfo or use CultureInfo.InvariantCulture when parsing numeric strings from external sources.

float.Parse()

csharp
1string input = "3.14";
2float result = float.Parse(input);
3Console.WriteLine(result);  // 3.14
4
5// With explicit culture (US uses '.' as decimal separator)
6float value = float.Parse("3.14", CultureInfo.InvariantCulture);

float.Parse() throws exceptions on invalid input:

csharp
1float.Parse("hello");  // FormatException
2float.Parse("");        // FormatException
3float.Parse(null);      // ArgumentNullException
4float.Parse("1e400");   // OverflowException
csharp
1string input = "3.14";
2
3if (float.TryParse(input, out float result))
4{
5    Console.WriteLine($"Parsed: {result}");  // Parsed: 3.14
6}
7else
8{
9    Console.WriteLine("Invalid number");
10}

TryParse never throws — it returns false and sets the output to 0 on failure:

csharp
1float.TryParse("hello", out float val);   // returns false, val = 0
2float.TryParse("", out float val2);        // returns false, val2 = 0
3float.TryParse(null, out float val3);      // returns false, val3 = 0
4float.TryParse("3.14", out float val4);    // returns true, val4 = 3.14

With culture info:

csharp
1// European format uses comma as decimal separator
2string europeanNumber = "3,14";
3
4float.TryParse(europeanNumber,
5    NumberStyles.Float,
6    CultureInfo.GetCultureInfo("de-DE"),
7    out float german);
8Console.WriteLine(german);  // 3.14
9
10// Invariant culture always uses '.' as decimal separator
11float.TryParse("3.14",
12    NumberStyles.Float,
13    CultureInfo.InvariantCulture,
14    out float invariant);
15Console.WriteLine(invariant);  // 3.14

Convert.ToSingle()

csharp
1float result = Convert.ToSingle("3.14");
2Console.WriteLine(result);  // 3.14
3
4// Handles null by returning 0 (no exception)
5float nullResult = Convert.ToSingle(null);
6Console.WriteLine(nullResult);  // 0
7
8// Throws on invalid strings
9Convert.ToSingle("hello");  // FormatException

Convert.ToSingle is essentially float.Parse with null handling. It delegates to float.Parse internally.

Comparison Table

MethodOn nullOn invalid stringReturns
float.Parse()ArgumentNullExceptionFormatExceptionfloat
float.TryParse()false, out = 0false, out = 0bool
Convert.ToSingle()0FormatExceptionfloat

Handling Special Values

csharp
1// Infinity and NaN
2float.TryParse("Infinity", out float inf);    // true, inf = ∞
3float.TryParse("-Infinity", out float negInf); // true, negInf = -∞
4float.TryParse("NaN", out float nan);          // true, nan = NaN
5
6// Scientific notation
7float.TryParse("1.5e3", out float sci);        // true, sci = 1500
8float.TryParse("2.5E-4", out float sci2);      // true, sci2 = 0.00025
9
10// Leading/trailing whitespace is handled
11float.TryParse("  3.14  ", out float ws);       // true, ws = 3.14
12
13// Currency symbols are NOT handled by default
14float.TryParse("$3.14", out float curr);        // false
15
16// With NumberStyles.Currency
17float.TryParse("$3.14",
18    NumberStyles.Currency,
19    CultureInfo.GetCultureInfo("en-US"),
20    out float usd);  // true, usd = 3.14

Practical Examples

csharp
1// Parsing user input
2Console.Write("Enter temperature: ");
3string input = Console.ReadLine();
4
5if (float.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out float temp))
6{
7    Console.WriteLine($"Temperature: {temp}°C");
8}
9else
10{
11    Console.WriteLine("Please enter a valid number.");
12}
13
14// Parsing CSV data
15string csvLine = "Alice,3.14,100.5";
16string[] parts = csvLine.Split(',');
17
18float[] values = parts
19    .Skip(1)
20    .Select(s => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out float v) ? v : 0f)
21    .ToArray();
22
23// Parsing with fallback
24float ParseOrDefault(string s, float defaultValue = 0f)
25{
26    return float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out float result)
27        ? result
28        : defaultValue;
29}

float vs double vs decimal

csharp
1// float — 7 digits of precision
2float f = float.Parse("3.14159265358979");
3Console.WriteLine(f);  // 3.1415927 (truncated)
4
5// double — 15-17 digits of precision
6double d = double.Parse("3.14159265358979");
7Console.WriteLine(d);  // 3.14159265358979
8
9// decimal — 28-29 digits, exact for base-10
10decimal m = decimal.Parse("3.14159265358979");
11Console.WriteLine(m);  // 3.14159265358979

Use float for graphics and game development (GPU operations). Use double for general-purpose math. Use decimal for financial calculations where exact base-10 representation matters.

Common Pitfalls

  • Not specifying culture for external data: float.Parse("3.14") may fail on a system with a French or German locale because those cultures use , as the decimal separator. Always pass CultureInfo.InvariantCulture when parsing data from files, APIs, or databases.
  • Using float.Parse() on user input without try/catch: If the user enters "abc", Parse throws a FormatException. Use TryParse for any input you do not fully control.
  • Precision loss with float: float has only 7 significant digits. float.Parse("123456789") becomes 123456792 due to precision loss. Use double (15 digits) or decimal (28 digits) when precision matters.
  • Assuming empty string returns 0: float.Parse("") throws FormatException, not 0. float.TryParse("", out var x) returns false with x = 0. Only Convert.ToSingle(null) returns 0, and even it throws on empty string.
  • Ignoring NumberStyles for special formats: Strings with currency symbols ($3.14), thousands separators (1,000.50), or parentheses for negatives ((3.14)) need appropriate NumberStyles flags. Default parsing rejects these formats.

Summary

  • Use float.TryParse() for safe parsing that never throws exceptions
  • Use float.Parse() when you are certain the input is valid
  • Always specify CultureInfo.InvariantCulture for data from external sources
  • Convert.ToSingle(null) returns 0; float.Parse(null) throws
  • float has 7 digits of precision — use double or decimal for higher precision
  • Use NumberStyles flags to handle currency symbols, thousands separators, and scientific notation

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.