programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Count the number of digits after the decimal point

Diedrie Redley
Greenhorn
Posts: 3
Here is what I am trying to solve: Given a Numbers instance, whose fields are arrays of all the built-in Java numeric types (int, long, float, double, big-decimal, etc), write a method to sort all the numbers into a master list, and then print out the numbers where the number of digits past the decimal point is equal to the index of the number in the master list.

Is there a function in Java that will give me just the numbers after the decimal? I tried Decimalformat but couldn't get it to work. Here is what I have so far; however, I think I might be on the wrong track. Can someone tell me if I'm taking the correct approach? Thanks.

Dee

Stephan van Hulst
Saloon Keeper
Posts: 7973
143
The best way to represent decimals with arbitrary precision is to use the BigDecimal class. So, for each number, see if you can find a way to convert it to a BigDecimal, using the desired precision.

Welcome to CodeRanch!

Stephan van Hulst
Saloon Keeper
Posts: 7973
143
you should probably split up your main method into smaller parts. Take a look at the problem description, you need fields of arrays of numeric types. I recommend using the Collection framework, so you can simply add new values to your numbers:

Diedrie Redley
Greenhorn
Posts: 3
Thank you. I'll give it a try.

Dee

Campbell Ritchie
Marshal
Posts: 56536
172
Welcome to the Ranch

As far as I can tell, the only type of number which has a concept of places right of the decimal point is BigDecimal. I suggest you ask your teachers what places right of the decimal point means in a double like 0.1 because you can add 0.1 to itself ten times and not get 1.0.
I shall try adding code tags to your post; they usually make it look much better

 It is sorta covered in the JavaRanch Style Guide.