Set the number of digits after the point in double

2019-06-20 04:47发布

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

标签: c# types double
3条回答
仙女界的扛把子
2楼-- · 2019-06-20 05:27

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?

查看更多
虎瘦雄心在
3楼-- · 2019-06-20 05:36

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")
查看更多
来,给爷笑一个
4楼-- · 2019-06-20 05:45

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

  if (Math.Abs(a - b) < 1E-4) {
    // close enough
    //...
  }
查看更多
登录 后发表回答