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?
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.
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.
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.
In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.
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);
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With