Josh
Josh

Reputation: 61

How to always show 3 numbers after decimal point C#

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?

Upvotes: 5

Views: 17446

Answers (3)

BrianV
BrianV

Reputation: 1

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

Upvotes: 0

Use the format in the toString

double pi = 3.1415927;
string output = pi.ToString("#.000");

Upvotes: 3

Timothy Shields
Timothy Shields

Reputation: 79531

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"

Upvotes: 8

Related Questions