• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Round double up with 2 digits....  RSS feed

 
Ranch Hand
Posts: 359
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a double with the value 4,85999999999 i want to round this value up too the closest value with 2 digits 4,86 i have looked in the math class, but i dont find the answer her.....

Do anyone have a good idea ??


Frank
 
Sheriff
Posts: 21423
94
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Keep in mind though that the double will become incorrect again if you do a lot of math with it. For example:

Output:
4.85999999999
486
4.86
4.86000000000001

This is caused because just like humans cannot write 1/3 without rounding at some point, PCs cannot write most decimal numbers (including 1/10) without rounding. That's because PCs use only factors of 2: ..., 32, 16, 8, 4, 2, 1, 1/2, 1/4, 1/8, ...
All numbers are constructed by adding these numbers, but at some point 1/10 will have to be rounded.

If you really want exact calculations with decimal numbers, either upgrade to ints / longs by multiplying with a fixed factor (e.g. with currencies use long cents instead of double dollars), or look at java.math.BigDecimal.
 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you want to round the number, or do you want to display/print the number rounded? If you want the latter, take a look at the DecimalFormat class.
 
Marshal
Posts: 59762
188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use J5.0 or J6 the printf method in System.out is easier than DecimalFormat.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!