Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one decimal for string format

Tags:

c#

asp.net

vb.net

I have below digits. I want to show one digit after to decimal. How to format it?

2.85
2
1.99

I was using ("{0:0.0}". But data showing like

2.9 //It should be 2.8
2.0 //It should be 2
2.0 //It should be 1.9
like image 388
James123 Avatar asked Nov 30 '10 06:11

James123


2 Answers

Try using "{0:0.#}" as the format string. However, that will only fix the .0. To fix the rounding to always round down, you might want to use:

string s = (Math.Floor(value * 10) / 10).ToString("0.#");
like image 63
Marc Gravell Avatar answered Oct 11 '22 03:10

Marc Gravell


Decimal[] decimals = { new Decimal(2.85), new Decimal(2), new Decimal(1.99) };

foreach (var x in decimals)
{
  Console.WriteLine(string.Format("{0:0.#}", Decimal.Truncate(x * 10) / 10));
}

// output
2.8
2
1.9
like image 42
cspolton Avatar answered Oct 11 '22 04:10

cspolton