Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Formatting in C#

Tags:

c#

I want a function that shows at most N decimal places, but does not pad 0's if it is unnecessary, so if N = 2,

2.03456 => 2.03
2.03 => 2.03
2.1 => 2.1
2 => 2

Every string formatting thing I have seen will pad values like 2 to 2.00, which I don't want

like image 637
Davis Dimitriov Avatar asked Jan 20 '23 20:01

Davis Dimitriov


2 Answers

How about this:

// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"
like image 152
David Heffernan Avatar answered Jan 31 '23 05:01

David Heffernan


Try this:

string s = String.Format("{0:0.##}", value);
like image 28
Jonathan Wood Avatar answered Jan 31 '23 05:01

Jonathan Wood