Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best approach rounding up decimals in C#

I've decimal value 18.8. Values that are stored in this variable can be of any kind. For example it can be 1.0000000 or 1.00004000 or 5.00000008. I would like to write a method so that I can pass decimal to it and get rounded up string. This wouldn't be a problem if I would know decimal places I would like to get. But what I would like to get is:

When it's 1.0000000 it should return 1.
If it's 1.00004000 it should return 1.00004.
When it's 5.00000008 it should return 5.00000008. So basically it should find all 0 that are behind last digit different then 0 and cut it off.

How should I approach it? What's the best method? I'm getting this value from SQL and put it in decimal variable but then i would like to display it and having 5.0000000 when it could be displayed as 5 is a bit overkill for me.

Hope I could get some nice suggestions.

like image 529
MadBoy Avatar asked Jan 18 '10 12:01

MadBoy


2 Answers

AFAIK, ToString( "0.##" ) will do, just increase number of # so that your value won't round up. E.g.:

decimal d = 1.999m;
string dStr = d.ToString("0.###");

This will generate "1,999" string (delimiter depends upon used culture).

As a result, you can use common very long formatting string: "0.############################" - to format all your values.

like image 91
terR0Q Avatar answered Oct 12 '22 22:10

terR0Q


So trim the zeroes from the end.

decimal d = 1.999m;
string dStr = d.ToString().TrimEnd('0').TrimEnd('.');
like image 37
Scoregraphic Avatar answered Oct 13 '22 00:10

Scoregraphic