Double floating point Subtraction

So, here comes a repeated question:

In one of my client's machine, i have this code,

        public double getFreeSpace()
        {
            return this.totalSize - this.listElements.Sum();
        }

and when subtraction like this happens: (1.0 - 0.8) the expected result is (0.2) but she gets the result some thing as 0.199999.

While this is not the intended result, how to get 0.2 as output for this code?

The stackoverflow question here, discusses the same issue but suggests using decimal as the alternative. (But, also note that in the same answer, we get a warning : It is a 128 bit datatype as opposed to 64 bit which is the size of a double).

I also tried, Math.Round(1.0-0.8, 0, MidpointRounding.AwayFromZero) but this does not do the job.

The question now is, how to get the desired answer as 0.2 while still keeping the same datatype as double without using a decimal ?

Answers


If the question is

how to get the desired answer as 0.2 while still keeping the same datatype as double without using a decimal

then the answer is: you can't.

I think you should take a look here to get some extra information.

The need for accuracy was the reason why the decimal type has been created. These types are slower to work with but are more accurate.


Need Your Help

JSF- How to get the previous selected row index from datatable?

jsf jsf-2 primefaces datatable

I want to retain the value of previously selected row index to compare it with the currently selected rown index.How can I able to get the previous index in backing bean from a datatable in jsf ?

Render Buffer on Screen in Windows

c++ c windows buffer render

I'm searching for a way rendering a char buffer onto the content-area of a window. This is just pseudo but intended to demonstrate what I actually want to do: