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.
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.
So trim the zeroes from the end.
decimal d = 1.999m;
string dStr = d.ToString().TrimEnd('0').TrimEnd('.');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With