Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Number of decimal places?  RSS feed

 
Mamady M
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to write a function which returns the number of decimal places a given number has (double). It sort of works... but not 100%.

Here is what i have so far:



The problem is that that is wont work with a number such as 115.0000 as it is assumed to be 115.0 when it is passed as a parameter.

Can someone help me? I tried looking at BigDecimal but cant think how i would use it.
 
Neeraj Dheer
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
apart from your problem, you might want to look at the String.indexOf() and allied methods.
 
Jon Egan
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem in the design approach of the "getNumberOfDecimals" method defined above is in the way numbers (including fractional numbers like doubles or floats) are stored in Java. The values of 115.0000 and 115.0 will look identical to your method, so there is no way for your method to determine which one was passed.

Try printing out the value of strNumber when this method is passed those two values, to see the problem explicitly.

-- Jon
 
Dilip Fernandez
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never heard of Regular Expressions? Try this.
 
Mark Spritzler
ranger
Sheriff
Posts: 17309
11
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Mr Mamady"-
Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it

here.

Thanks! and welcome to the JavaRanch!

Mark
 
Mamady M
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neeraj Dheer:
Thank you, have used indexOf instead of my little for loop.

Jon Egan:
I actually did try it, and that is why i asked here, i thought maybe there is a way to work around this without me actually having to change the type of the parameter. I guess not

Dilip Fernandez:
I have used regular expressions in many other places, i didnt actually know java supported it. Also, your example still requires me to convert my number to a string before i can process it, i wanted to keep it as a double.


Anyways, thanks for all your help, i have simply converted the number into a string before passing it to the method, i didnt really want to do this, but i had no choice i guess.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!