5

I am currently displaying a number that is being rounded to 3 decimal places e.g. 0.31, using Math.Pow, the only problem is I want to display this number to say 0.310 (for styling purposes) does anyone know if this is possible?

Josh
  • 61
  • 1
  • 1
  • 2
  • Sure, take a look at the ToString method and giving it the formatting: https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx and also: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx – Ahmed ilyas Apr 10 '16 at 17:36
  • This question was said to be a duplicate of http://stackoverflow.com/questions/3814190/limiting-double-to-3-decimal-places Looking at the answers, it's clear a different question was being asked there. The question here is not involving a value that simply should have been computed using `decimal`. If you really do want to use `double` or `float`, then doing something like `Math.Truncate(x * 1000) / 1000` isn't going to work. For example, `0.001` is not exactly represented by any `double`, but if you do `((double)0.001).ToString("F3") you will get "0.001". – Timothy Shields Apr 10 '16 at 17:42

3 Answers3

7

The Fixed-Point Format Specifier can be used in a call to ToString or in string.Format:

double x = 1493.1987;
string s1 = x.ToString("F3");
string s2 = string.Format("Your total is {0:F3}, have a nice day.", x);
// s1 is "1493.199"
// s2 is "Your total is 1493.199, have a nice day."

Note that the Fixed-Point Format Specifier will always show the number of decimal digits you specify. For example:

double y = 1493;
string s3 = y.ToString("F3");
// s3 is "1493.000"
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
3

Use the format in the toString

double pi = 3.1415927;
string output = pi.ToString("#.000");
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Here is an updated example that also works w/o having to call .ToString():

float a = 12.3578f;
double b = 12.3578d;
Console.WriteLine("The tolerance specs are: {0:F4} and: {1:F3}", a,b);

ANSWER: The tolerance specs are: 12.3578 and: 12.358

BrianV
  • 1
  • 1