Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder.Append with float

Tags:

c#

asp.net

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.

like image 909
rick schott Avatar asked Jan 23 '23 18:01

rick schott


2 Answers

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.

like image 137
SLaks Avatar answered Feb 01 '23 06:02

SLaks


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);
    }
}
like image 45
Andrew Hare Avatar answered Feb 01 '23 05:02

Andrew Hare