• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can i limit double type calculation results to desired decimal point precision?  RSS feed

 
Mohammad Nizam Uddin
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written this code. the input arguments are all double type. the result is in 12 decimal point precision like obj1 volume is: 16777.216000000004. But i want to get the results only in 2 decimal point precision like obj1 volume is: 16777.22. How can I achieve that?

 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do the same as below:

 
Stefan Evans
Bartender
Posts: 1837
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java.text.DecimalFormat class will support formatting of a number to two decimal places.

Probably more appropriate for you is the format method of java.io.PrintWriter.
The format syntax can be found here

(edit: seeing as the guy above me already posted some code)
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stefan Evans wrote:The java.text.DecimalFormat class will support formatting of a number to two decimal places.

I dint find any such limit in the Javadocs.


Though System.out.format is easier choice.

 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tushar.

You are correct, there isn't any limit.
My statement was to tell the OP that it was possible, not to indicate a limit - though reading it now I realize the "to" can be mis-interpreted.

As you demonstrated, the DecimalFormat class does support formatting of a number to two decimal places. It can be configured to display more if you wish .
Also, I would have used the pattern "0.00" rather than "#.##" just so that it would display 2.20 and not 2.2 if that least significant figure was a 0.
But thats just a carry-over from high school physics classes



 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stefans, i was in doubt there was any limit or something like that.. But yes as you suggested to use System.out.format is seems to be better option.

 
Mohammad Nizam Uddin
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stefan Evans wrote:


Thanks for the code Stefan.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!