Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I remove decimal part of double?

 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a function that I'm working with that returns a double with a very long decimal part tacked onto it. The units the double represents are so precise that I can just lose the decimal part. I was thinking of using a StringBuffer to parse the double and remove the offending decimal. Anyone know an easier way to do this?


 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use a DecimalFormat.
 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply. In all honesty, though, that seems to be a lot more complex than my original idea. I'm only dealing with two numbers here, and implementing a DecimalFormat seems to be a bit much.
Originally posted by Cindy Glass:
Use a DecimalFormat.

 
Paul Stevens
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a Double and the intValue() or longValue() method of Double.
[This message has been edited by Paul Stevens (edited September 28, 2001).]
 
shilpa kulkarni
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or, you can use the NumberFormat class, this way u can set the number of digits after decimal that u want.
here is an example :
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you just want to drop the fractional part entirely and round to the nearest integer, it's quite simple:
<pre> int intVal = (int) doubleVal;</pre>

[This message has been edited by Jim Yingst (edited September 28, 2001).]
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And if you want to round differently, it's almost as simple - explore java.lang.Math (e.g. Math.floor() etc).
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic