Click here to Skip to main content
15,882,114 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
Silly question but I need to convert a String I have read from a file to a floating point number i.e. "0.45" to 0.45. A method I have used in the past was to do a
string strValue = "0.45";
fltValue = strValue.ToDouble();

This gave a floating point number I seem to remember but it was BIG.
Is there a simple, quick means of getting a two digit number?
I have seen a ConvertTo.Decimal() and a ConvertTo.Double(), Just trying to do it right!

What I have tried:

Uncle Google, MSDN Docs, Adding the ToDouble() and the ConvertTo and tried to cast the value using the C methods
Max_Value = (float)StrMax_Value;
Richard MacCutchan 26-Feb-24 6:00am    
There is no such thing as "digits" in floating point values*. That is only relevant when you display the number using one of the format patterns.

*Floats and doubles are stored in scientific format: sign:exponent:mantissa.

This gave a floating point number I seem to remember but it was BIG.
What do you intend, with 'BIG'?
You know, double data size is 8 bytes (independently by the conversion method you're using).

What's wrong with Double.Parse Method (System) | Microsoft Learn[^] and Double.TryParse Method (System) | Microsoft Learn[^]?
Share this answer
Maciej Los 26-Feb-24 11:14am    
CPallini 27-Feb-24 2:12am    
Thank you!
glennPattonWork3 26-Feb-24 15:04pm    
I was a little rushed when I typed that, BIG meant 32 bytes with compiler that was used it was for a embedded system.
I believe the correct way would be like
string strValue= "0.45"; 

if (string.IsNullOrEmpty(strValue))
  // Handle the case of null or empty string (e.g., return default value, throw exception)
  Console.WriteLine("String is null or empty.");
  return; // Or throw an exception

// Proceed with conversion only if the string is not null or empty
float floatValue;

if (!float.TryParse(strValue, out floatValue))
  // Handle the case of invalid format or raise Exception
  Console.WriteLine("Invalid number format.");

//Conversion successful, use floatValue

Ideally, you should have a Helper Class with helper functions like ConvertToFloat in which you embed the above logic to have a consistent output.
Share this answer
glennPattonWork3 26-Feb-24 6:37am    
Appears to work, thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900