Double data type count number of decimal places?

G

Guest

I require a function that takes a double as a parameter and returns the number of decimal places. What is the most efficient way in c# to find out the number of decimal places

I have written a function that does it by converting the double to a string. Is there a better way

public static int CountDecimalPlaces(double double1)

return double1.ToString().Substring(double1.ToString().IndexOf(".")+1).Length


Thank yo
 
J

Jeffrey Tan[MSFT]

Hi android,

Based on my understanding, you want to get the decimal length of your
double value.

As I think your solution of using ToString should be a good way, and can be
good to read.

Use other solution, I think you may use some number operation, which may
need loop. You may also get the correct result, but they will have less
readability.

For performance issue, I think this will not have much performance problem,
other solution may not be better than yours.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

Jon Skeet [C# MVP]

android said:
I require a function that takes a double as a parameter and returns
the number of decimal places. What is the most efficient way in c# to
find out the number of decimal places?

That's not really a particularly useful measure - a double value is
likely to have lots of decimal places which may not be useful to the
caller. For instance, the exact value of the double given by the
literal 0.1 is

0.1000000000000000055511151231257827021181583404541015625

Now, chances are the caller is really only interested in 1 decimal
place - but you can't actually tell.

Using ToString("R") will give you (I believe) the shortest form of the
double which can always be parsed back to the same double, which is one
measure which might be useful to you.

See http://www.pobox.com/~skeet/csharp/floatingpoint.html and
http://www.pobox.com/~skeet/csharp/decimal.html for more information.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top