6

In c# double type how can i set the number of digits after the point, i need only 4. thank you.

TrueWill
  • 25,132
  • 10
  • 101
  • 150
Bassel Shawi
  • 604
  • 4
  • 11
  • 29
  • 2
    inputValue = Math.Round(inputValue, 4); Adapted from http://stackoverflow.com/questions/2357855/round-double-in-two-decimal-places-in-c – jade290 Sep 25 '13 at 23:29

3 Answers3

7

You can't. Binary floating point doesn't work like that. You can format a double that way (e.g. using "f4" as the format string), but if you're dealing with values which have a natural number of decimal places, then you should probably be using decimal instead. Could you give us more information about what your values represent?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • i m doing an equality between 2 points's x and there values are 5.0000 and 4.999999996 and i need it te be true – Bassel Shawi Feb 20 '10 at 19:02
  • @Bass: If you're only doing an equality test, then nobugz's answer is probably the right way to go. I would still consider whether you want to use decimal instead though - it depends on the kind of values you've got. – Jon Skeet Feb 21 '10 at 07:28
3

You can't set the number of digits after the point on the double directly.

You can change the string representation of the double using a format string.

One example would be:

string.Format("{0:0.####}", number);

Or as Jon Skeet points out:

number.ToString("f4")
John Weldon
  • 39,849
  • 11
  • 94
  • 127
2

Use this to compare two floating point numbers to 4 digits in the fraction:

  if (Math.Abs(a - b) < 1E-4) {
    // close enough
    //...
  }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • If you want to be absolutely sure they are equal then it should be Double.epsilon rather than 1e-4. If you want to say they are 'close enough' equal then you're code is fine – zebrabox Feb 20 '10 at 20:25
  • Double.Epsilon cannot work as-is, it is far too small. A proper epsilon is something like a * 1E-15 but that has to be incremented for errors accumulated by each FP operation. – Hans Passant Feb 20 '10 at 20:46