Reputation: 12005
If you run this code:
decimal d1 = 0m;
decimal d2 = 0.0m;
decimal d3 = 0.0000m;
string str1 = d1.ToString(System.Globalization.CultureInfo.InvariantCulture);
string str2 = d2.ToString(System.Globalization.CultureInfo.InvariantCulture);
string str3 = d3.ToString(System.Globalization.CultureInfo.InvariantCulture);
You get :
str1: "0",
str2: "0.0",
str3: "0.0000"
Is there some way in code to get the number of decimal places (as would be output by decimal.ToString above) in the decimal variables ?
i.e. want to get:
d1: 0
d2: 1
d3: 4
(In case anyone is wondering why this is required, it is for some workaround code for a problem involving SSRS and Excel: http://social.technet.microsoft.com/Forums/sqlserver/en-US/5c4fc104-5d69-409d-9a6e-a6354922729a/exporting-ssrs-report-to-excel-2007-excel-found-unreadable-content-in-file-xlsx)
EDIT:
Title has been changed. Sorry for the confusion, guys. In the underlying problem I'm trying to solve, the decimals are always 0 - hence the confusion.
Upvotes: 2
Views: 4889
Reputation: 186668
Unsignificant digits are those that are between decimal separator and first non-zero digit providing that the number has zero integer part, e.g.:
0.000 - 3 unsignificant digits
0.0001 - 3
0.000100 - 3 unsignificant digits (not 5!)
0.12301 - 0
0.1230 - 0
0.0123 - 1
1.0 - 0 unsignificant digits (not 1!)
1.0000 - 0 unsignificant digits (not 3!)
-0.0001 - 3
So, the solution can be
public static int UnsignificantDigits(Decimal value) {
int result = 0;
String St = value.ToString(CultureInfo.InvariantCulture);
if (St.StartsWith("0.") || St.StartsWith("-0."))
for (int i = St.IndexOf('.') + 1; i < St.Length && St[i] == '0'; ++i)
result += 1;
return result;
}
...
int count = UnsignificantDigits(0.000m); // <- returns 3
Upvotes: 1
Reputation: 101681
decimal d3 = 0.0000m;
bool control = true;
string str = d3.ToString(CultureInfo.InvariantCulture);
int zeroCount = str.Select((c, index) =>
{
if (index > str.IndexOf('.') && c == '0' && control) return 1;
control = false;
return 0;
}).Sum();
Upvotes: 1
Reputation: 12005
Thanks to @V4Vendetta for pointing me to the other question.
This does the trick:
int count = BitConverter.GetBytes(decimal.GetBits(yourDecimalHere)[3])[2];
(From: https://stackoverflow.com/a/13493771/70140)
Upvotes: 0
Reputation: 10694
I think as this is what u need as MarcinJuraszek said
decimal d = 0.0000m;
int count = d.ToString(CultureInfo.InvariantCulture).
Substring(d.ToString(CultureInfo.InvariantCulture).
IndexOf(".") + 1).Length;
Upvotes: 2