• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to trim double value

 
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


How do i trim the double values upto two decimal places?
9.870000000000001 should be 9.87
4.609999999999999 should be 4.61
Why this values are different ?

Thanks in advance
 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is normal behaviour for floating-point aruthmetic. It is like calculating 1/3 = 0.333333333333333333 in decimal, then 1/3 * 3 = 0.999999999999999999 and when you subtract it from 1 you get 0.00000000000000000001. (Or something like that.) There are some numbers which cannot round like that at all, which is why you are getting numbers ending with 0000000001 or 9999999999.
That is why you shouldn't use floating point arithmetic for money or as the counter for a for loop.

Suggest what you actually want is to print out the numbers with a particular precision, rather than rounding.

Try the % tags which are described in the API for the Formatter class. There is more about the % tags in the Java Tutorial here. You probably want something like
System.out.printf("Number = %6.2f%n", doubleNumber);
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Links to more in-depth explanations about floating point acccuracy can be found under #20 in the http://faq.javaranch.com/java/JavaBeginnersFaq
 
Eat that pie! EAT IT! Now read this tiny ad. READ IT!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic