-1

In .NET, when I subtract 1.35 from 1.35072 it shows .000719999999. How could I get .00072 when using a double?

TOTKILO.Text = KILO.Text * TOUCH.Text * 0.01;    //here 1.35072
TextBox10.Text = TextBox9.Text * TextBox8.Text * 0.01; //here 1.35
K = Val(TOTKILO.Text) - Val(TextBox10.Text);  //here it shows 0.00719999
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mukesh
  • 9
  • 2
  • 2
    Your question is very unclear - please can you try and edit your question to make it easier to understand what it is you are trying to do and what you are having problems with. – Justin Mar 08 '11 at 04:12
  • 8
    @eldarerathis You should get a medal or something! – Justin Mar 08 '11 at 04:34
  • 1
    @Kragen: I'll gladly accept one if they're being distributed, but only if I get to stand on a nifty podium, too. – eldarerathis Mar 08 '11 at 04:37
  • 8
    Ha, wow, just checked out @eldarerathis's mighty edit... I wish you could upvote edits! – Dan Tao Mar 08 '11 at 05:50
  • 1
    Wow, eldarerathis's edit really saved this question. Casting final re-open vote... – Mysticial Oct 18 '11 at 06:34

3 Answers3

5

Depends on what you're really asking.

If you want to round to five decimal places, you can just do:

double x = 1.35072;
double y = 1.35;
double z = Math.Round(x - y, 5); // 0.00072

If, on the other hand, your goal is to always get precise results from adding/subtracting decimal numbers, use the decimal type instead of double since it is inherently a base-10 type (as opposed to a base-2 type) and can therefore represent numbers expressed in decimal form precisely.

decimal x = 1.35072M;
decimal y = 1.35M;
decimal z = x - y; // 0.00072M
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
0

Doubles and floating points are always represented with a varying degree of precision than what we visualize them to be. Always round up the values to few decimals and then check the answers.

Additional details are in How To Work Around Floating-Point Accuracy/Comparison Problems.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Saravanan
  • 7,637
  • 5
  • 41
  • 72
0

From what I've seen, you almost never actually need a double. Nearly all the time a decimal (System.Decimal) works for what you need, and it is an exact number, not a floating point representation, so you'll never have these rounding problems.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • 1
    Never have rounding problems? So `1M - (1M / 3M)` will give me an exact result? (Just giving you a hard time ;)) – Dan Tao Mar 08 '11 at 04:38