Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 805
Trong Tran Avatar asked Nov 23 '15 08:11

Trong Tran


People also ask

Why can't I convert a string to a float?

If you convert a string object into a floating-point in Python many times you will get a ValueError: could not convert string to float. Usually, this happens if the string object has an invalid floating value with spaces or comma Python will throw ValueError while parsing into string object into float.

Can string be converted to float?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

Why can't I convert a string to a float in Python?

The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.

Can you convert string to int or float?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.


2 Answers

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);
like image 70
Dmitry Bychenko Avatar answered Oct 19 '22 20:10

Dmitry Bychenko


// 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.

like image 29
Saeb Amini Avatar answered Oct 19 '22 18:10

Saeb Amini