Trong Tran
Trong Tran

Reputation: 686

Why is converting between string and float wrong?

Please see my example below.

float maxFloat = float.MaxValue;
string s = maxFloat.ToString();
float result = float.Parse(s); // same with Convert.ToSingle(s);

bool mustEqual = (maxFloat == result);
// It returns FALSE, why?

Upvotes: 32

Views: 4106

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You should use "R" format string:

https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx.

https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#RFormatString

"R" or "r" Round-trip Result: A string that can round-trip to an identical number. Supported by: Single, Double, and BigInteger. Precision specifier: Ignored.

  float maxFloat = float.MaxValue;
  string s = maxFloat.ToString("R"); // <- "R"
  float result = float.Parse(s);

  bool mustEqual = (maxFloat == result);

Upvotes: 47

Saeb Amini
Saeb Amini

Reputation: 24390

// It returns FALSE, why?

Because float.ToString() outputs a 7-digit precision number by default, so your float.MaxValue which has a value of 3.40282347E+38 (9-digit precision) will become rounded to 3.402823E+38 and your check fails because of course 3.402823E+38 != 3.40282347E+38.

If you explicitly specify a format specifier to output float.MaxValue with 9-digit precision, e.g. float.MaxValue.ToString("G9"), your check will succeed.

Upvotes: 29

Related Questions