Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
At present I am working on piece of C++ code in which I need to read data from a database, and if database value is non-zero, then I need to apply some further logic.

But in the database there are values which are being calculated and can come out as -0.0. And this negative zero is being treated as Garbage value in C++ double variable. I have already initialized the value as 0.0 in constructor.

C++
// This list is being populated from Database
for (Sample::List<BalanceSheet>::Iterator i((Sample::List<BalanceSheet> &) Balance.Entries()); i.HaveItem(); ++i) 
{
    if (SomeCondition != "")
    {
        // This is where am getting Garbage values since GetBalance() returns -0.0
        if (i->GetBalance() != 0) 
        {
            DoOperation();
        }
    }
}
Posted
Updated 30-Nov-15 21:55pm
v3
Comments
Sergey Alexandrovich Kryukov 30-Nov-15 14:37pm    
How can this garbage be related to garbage collection? :-)
—SA
enhzflep 30-Nov-15 18:14pm    
Well, if you'd be kind enough to ask a question it will surely expedite the process.
Richard MacCutchan 1-Dec-15 3:14am    
If you are using doubles to hold financial values you are in for a whole heap of trouble.

This is not about garbage collection but about sound programming practices.
Doubles are not integers - while obvious this has subtle consequences. It is unlikely that the value is actually -0.0 but in fact a very small negative number which can be shown using your debugger. Doing this this would have answered the question for you.

Never test a double in this way:
C#
if (i->GetBalance() != 0) // This is a bug waiting to happen
Read here: https://isocpp.org/wiki/faq/newbie#floating-point-arith[^]
 
Share this answer
 
v3
Comments
CPallini 1-Dec-15 3:20am    
My 5.
George Jonsson 1-Dec-15 3:58am    
Good answer. +5
A C/C++ floating point value has always a defined state and is never "garbage". It is up to you handle special states like NaN (not a number), infinity, denormalized numbers and signed zeroes (yes, negative zero is a valid state). To see what your value is exactly print it out using a function that uses printf formatting setting the max. precision for doubles (format "%.15E").

However, the value may be "garbage" from the point of view of your application. Then you should handle such values accordingly. To avoid such values, ensure that only valid values (again from the point of view of your application) are written to the database.
 
Share this answer
 

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