StringBuilder.Append
using float
is truncating the value. What is it converting to and how can I stop it from truncating?
AttributeOrder
is type float
and I am losing precision when building the string.
if ( AttributeOrder != 0 )
{
if ( Result.Length > 0 )
{
Result.Append( " AND " );
}
Result.Append( COLUMN_ATTRIBUTE_ORDER );
Result.Append( "=" );
Result.Append( AttributeOrder );
}
EDIT: This is legacy code, I cannot change the underlying datatypes. The column in SQL Server is a real and the datatype is float
. I need to present the float
as it is filled, as a string for other purposes and not loose precision as is.
You can convert the float
to a string using a format string, like this:
Result.Append(AttributeOrder.ToString("G9"))
Or, alternatively,
Result.AppendFormat("{0}={1:G9}", COLUMN_ATTRIBUTE_ORDER, AttributeOrder)
However, you will not be able to get more than 9 digits of precision from a float
, and digits 8 and 9 will be inaccurate.
The float
datatype can only hold seven digits of precision. As soon as you put the value into a float
variable, you've irrecoverably lost the precision. In order to store all 24 digits of precision from SQL Server, you need to use the decimal
datatype.
Once you change the variable to a decimal
, Append
will give you as many digits as you put in.
If you need to provide a representation of a floating-point number then you should use System.Decimal
- System.Single
cannot accurately represent the precision you are looking to display.
This simple example shows the difference:
using System;
class Test
{
static void Main()
{
Single s = 1.23456789f;
Decimal d = 1.23456789m;
Console.WriteLine(s);
Console.WriteLine(d);
}
}
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