• Post Reply Bookmark Topic Watch Topic
  • New Topic

Display user defined number of decimals  RSS feed

 
Jackson Van Dyke
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

How can I get a user to define the number of decimal places they wish to display from a number with a large amount of decimal places, such as Pi? I was directed to one of the Oracle turorials, this one: docs.oracle.com/javase/tutorial/java/data/numberformat.html/[url=docs.oracle.com/javase/tutorial/java/data/numberformat.html although I either missed something there or it isn%27t what I need. If you need any clarification or otherwise, I will be happy to help.
Any help would be greatly appreciated.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DecimalFormat is possibly a better class for you.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jackson Van Dyke wrote:Any help would be greatly appreciated.

Michael's suggestion is probably the most Object Oriented; although, as an old C hack, I have to admit a liking for String.format() (or PrintStream.printf() - the two are basically the same).should do the trick for any float, double or BigDecimal 'value', providing requestedDecimals is >= 0. A non-FP type (eg, an int) will throw IllegalFormatConversionException.
It should be noted that it will produce fixed-format output, regardless of the supplied value, including trailing '0's if requestedDecimals is too big for the type, and also any discrepancies due to inexact values; so, for example:
display(0.1f, 20)
returns
0.10000000149011612000

HIH

Winston
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What’s non-object-oriented about printf? It uses a Formatter object behind the scenes.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:What’s non-object-oriented about printf? It uses a Formatter object behind the scenes.

Yeah, you're probably right. I just think of it as more procedural than something like DecimalFormat.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!