Float type in database but the number becomes different after getting to C#

Jikha 1 Reputation point
2020-11-26T23:22:55.097+00:00

In database, there is a field in "float" type.
There is a record with 300.88. (correct value)
After getting into DTO ("double" type), it becomes 300.87999988
After passing DTO to textbox in view, it displays 300.88 correctly.

When saving the record, it is required to compare with database record.
The program treat it as that the value is modified but actually not. (300.88 in textbox value vs 300.87999988 get from db to the double type property )

What should be changed? Can I keep the database type as float and just change program?

Thank you.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,362 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Viorel 112.9K Reputation points
    2020-11-27T08:57:22.55+00:00

    Maybe you should not round the value before displaying in textbox; or use double.ToString(“R”).

    I think that you should consider the decimal type in DTO and money or decimal in database. Is it mandatory to keep the database unchanged?

    If it is not possible to improve the database, then maybe keep the original double value. If the textbox was changed, then use the edited value. Otherwise use the kept value.

    1 person found this answer helpful.
    0 comments No comments

  2. Karen Payne MVP 35,196 Reputation points
    2020-11-30T12:03:23.123+00:00

    Hello @Jikha ,

    If you don't need precision of more than two decimal places then consider using decimal type.

    You can test (here with SQL-Server) the outcome as follows.

    DECLARE @FoatValue float(18)= 299.87999988;  
    WHILE @FoatValue < 301.0  
        BEGIN  
            PRINT 'float: ' + cast(cast(@FoatValue as decimal(10,2)) AS varchar(10)) + '   as decimal: ' + cast(@FoatValue AS varchar)  
            SET @FoatValue+=0.01;  
        END;  
    
    1 person found this answer helpful.
    0 comments No comments

  3. Cheong00 3,471 Reputation points
    2020-11-27T02:08:37.413+00:00

    What is the database you're using? I think possibly the value stored there is 300.87999988 already and you should expand the data type in database.

    See the value in action: https://dotnetfiddle.net/QAsHlh You can see the value is not displayed exactly even if I added that many decimal places to show.


  4. Bonnie DeWitt 811 Reputation points
    2020-12-06T01:41:03.367+00:00

    I agree with @Viorel and @Karen Payne MVP ... you probably should use decimal rather than double (in the DTO). And don't use float in the database (use decimal or money, as Viorel suggested). Hopefully you can change the database column.

    This may be of interest, a blog post I wrote a few years ago discussing Double vs Decimal:

    double-vs-decimal.html

    0 comments No comments