views:

383

answers:

4

Hello,

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 diffrent then 0 and cut it off.

How should i aproach 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.

With regards,

MadBoy

+6  A: 

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.

terR0Q
I don't know amount of decimal places i need. This would work if i would know that i want to cut it off after 3 digits or more. But i want to cut it off only if all digits are zeros after the last non zero.
MadBoy
If you have 1.00004000, then after ToString("0.####################") you'll have "1.00004". Speaking of MAX of # signs: it is 28. Decimal allows maximum of 28-29 of significant digits. This makes 1 for leading zero and 28 for other signs. Even if you have smth like 15555.98900008900 it will be ok.
terR0Q
Thanks, it works. I should have tested it before doubting it will work as you said it would.
MadBoy
+2  A: 

So trim the zeroes from the end.

decimal d = 1.999m;
string dStr = d.ToString().TrimEnd('0').TrimEnd('.');
Scoregraphic
And if there's a value 1,000,000.00? Then he loses all zero's I suppose? Or there remains "1,000,000."
Webleeuw
He loses only the zeroes after the dot (.) There remains the dot, but he could just add another `TrimEnd('.')`. For I18N, he should not use the dot, but the culture specific separator.
Scoregraphic
A: 

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

Grzenio
How is an article discussing *binary* floating point relevant to the `decimal` type that the question asks about?
LukeH
+1  A: 

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"
Jonas Elfström