VB.NET Subtraction Problem


I'm currenty using VS.NET 2003 .NET 1.1 and am experiencing a very strange problem.

        Dim x As Double, y As Double, z As Double

        x = 10.2
        y = 3
        z = x - y

At the end of this z is always  7.199999999999993

Where do all of these decimal places come from? I'm sure there's a very simple answer or I haven't got something set right, but I can't find it.

Thanks in advance,
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
It is based on the precision for double.  If you don't need it, don't use it--use singles instead.

Dim x As Single, y As Single, z As Single

x = 10.2
y = 3
z = x - y

HBPROCKAuthor Commented:
I see your point Bob, but in certain circumstances (i.e my calculator) I will require a dynamic range of results.

Many more DP may be required, but smaller sums like this will still need to return an accurate result without seemingly erronious variation. Using rounding is not an option...

Could you explain to me where this variation from the math logic comes from? Being a VB6 developer, I've always been used to receiving the 7.2 expected from this calculation.

Many Thanks,
Bob LearnedCommented:

Double precision numbers store an approximation of a real number.

When you work with floating-point numbers, keep in mind that they do not always have a precise representation in memory. This could lead to unexpected results from certain operations...

You only need as much precision from the result that you have with the input:

z = Math.Round(z + .005, 1)


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HBPROCKAuthor Commented:
This is the information I needed...

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.