Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always show 3 numbers after decimal point C#

Tags:

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?

like image 438
Josh Avatar asked Mar 12 '23 15:03

Josh


2 Answers

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"
like image 118
Timothy Shields Avatar answered Mar 23 '23 07:03

Timothy Shields


Use the format in the toString

double pi = 3.1415927;
string output = pi.ToString("#.000");
like image 23
ΦXocę 웃 Пepeúpa ツ Avatar answered Mar 23 '23 07:03

ΦXocę 웃 Пepeúpa ツ