• 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

Formatting decimals

 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I need to get he value 8.5679 as 8.56 and 8.5649 as 8.56. That is truncating the decimals after the second digit. Please advice.

Than ks,
Francis
 
Ranch Hand
Posts: 814
Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See DecimalFormat
 
francis varkey
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which method ?
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mmm, NumberFormat won't really do it for you, as it uses proper rounding, not truncation. Unless of course you wish to abandon truncation for something that, well, makes much more sense?

That is to say: in the real world, 8.5679 should really be rounded to 8.57 rather than 8.56, as the former is a much closer approximation. Do you really need to represent this as 8.56?

If, for some reason, you really do need this, I suggest looking at Math.floor(). Of course, this only rounds down to the nearest lower integer value. But, hey - that's what basic math operations like multiplication and division are for. (Well, one reason for their existence, anyway.) Consider: what happens if you multiply a value by 100? And what happens if you divide by 100? With a few simple mathematical operations, you can achieve the result you desire - if indeed you still do desire it.
 
Ninad Kulkarni
Ranch Hand
Posts: 814
Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@ francis
Mike is perfectly correct

See the code example given below



Output
8.56
8.56
 
I RELEASE YOU! (for now .... ) Feel free to peruse this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic