15,877,675 members
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;`
Posted
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.

Solution 1

Quote:
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[^]?

Maciej Los 26-Feb-24 11:14am
5ed!
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.

Solution 2

I believe the correct way would be like
C#
```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.

v2