30

I'd like to dispaly only one decimal place. I've tried the following:

string thevalue = "6.33";
thevalue = string.Format("{0:0.#}", thevalue);

result: 6.33. But should be 6.3? Even 0.0 does not work. What am I doing wrong?

leppie
  • 115,091
  • 17
  • 196
  • 297
4thSpace
  • 43,672
  • 97
  • 296
  • 475

6 Answers6

34

Here is another way to format floating point numbers as you need it:

string.Format("{0:F1}",6.33);
hendrik
  • 1,902
  • 16
  • 14
30

You need it to be a floating-point value for that to work.

double thevalue = 6.33;

Here's a demo. Right now, it's just a string, so it'll be inserted as-is. If you need to parse it, use double.Parse or double.TryParse. (Or float, or decimal.)

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    it works perfectly but it would round the numbers like `0.155` to `0.2`..Its a small problem though! – Anirudha Aug 27 '12 at 17:06
21

Here are a few different examples to consider:

double l_value = 6;
string result= string.Format("{0:0.00}", l_value );
Console.WriteLine(result);

Output : 6.00

double l_value = 6.33333;
string result= string.Format("{0:0.00}", l_value );
Console.WriteLine(result);

Output : 6.33

double l_value = 6.4567;
string result = string.Format("{0:0.00}", l_value);
Console.WriteLine(result);

Output : 6.46

Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
15

ToString() simplifies the job. double.Parse(theValue).ToString("N1")

Marcelo de Aguiar
  • 1,432
  • 12
  • 31
1

option 1 (let it be string):

string thevalue = "6.33";
thevalue = string.Format("{0}", thevalue.Substring(0, thevalue.length-1));

option 2 (convert it):

string thevalue = "6.33";
var thevalue = string.Format("{0:0.0}", double.Parse(theValue));

option 3 (fire up RegEx):

var regex = new Regex(@"(\d+\.\d)"); // but that everywhere, maybe static
thevalue = regexObj.Match(thevalue ).Groups[1].Value;
TheHe
  • 2,933
  • 18
  • 22
1

Please this:

String.Format("{0:0.0}", 123.4567); // return 123.5
barbsan
  • 3,418
  • 11
  • 21
  • 28
duc14s
  • 181
  • 3
  • 4