MadBoy
MadBoy

Reputation: 11104

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.

Upvotes: 9

Views: 1832

Answers (4)

Jonas Elfström
Jonas Elfström

Reputation: 31428

You can also use string.Format and here's the documentation of the different possible formats but I like Johan Sheehans cheat sheet more as a quick reference.

decimal number=4711.00004711m;
4711.00004711
string.Format("{0:0.#############}",number);
"4711,00004711"
number=42;
42
string.Format("{0:0.#############}",number);
"42"

Upvotes: 1

Scoregraphic
Scoregraphic

Reputation: 7200

So trim the zeroes from the end.

decimal d = 1.999m;
string dStr = d.ToString().TrimEnd('0').TrimEnd('.');

Upvotes: 2

terR0Q
terR0Q

Reputation: 1367

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.

Upvotes: 10

Grzenio
Grzenio

Reputation: 36649

Take a look at Jon Skeets article: http://www.yoda.arachsys.com/csharp/floatingpoint.html

Upvotes: -2

Related Questions