• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with doubles equalling ints  RSS feed

 
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I was trying to answer one of the algorithm problems on TopCoder whereby a message is displayed only if the percentage of seconds elapsed is exactly10.00000%, 11.000000% etc.

You have to parse a time string and convert it to seconds and then see how many messages will be displayed in total. 0% and 100% will never be displayed. My implementation is as follows:



I was getting incorrect counts and when I checked my output by entering 00:01:40 as the time string and putting in the println() statements shown above I saw that a few of the double values weren't exactly on a certain number, but were (for instance) 28.999999996. So converting this to an int and comparing values will always give a wrong result. What I can't understand is why (29.0 / 100.0) * 100.0 would ever give me something other than 29.0 and also how should I have implemented the algorithm?

Cheers

Joe
 
Ranch Hand
Posts: 93
IntelliJ IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Joe: If you need to use decimal numbers without loosing precision you must use BigDecimal NEVER float or double.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!