This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

decimal precision

 
Nijeesh Balan
Ranch Hand
Posts: 116
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,
I have a simple requirement. I just want to maintain two digits after the decimal point (they should not be rounded off).
for eg., if the value is
i/p -> 3333.8967 ; o/p -> 3333.89
i/p -> 23.8; o/p -> 23.80
i/p -> 4.982 ; o/p -> 4.98
which is the best way to accomplish this?
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One approach is to multiply the value by 100, convert to integer (or long), then divide by 100.0 and assign back to float/double.
For example:
double dval = 3333.8967;
int ival = (int)(dval * 100);
dval = ival / 100.0;
There is still the danger of a round-off occuring. After multiplying the above by 100 you would get 333389. However after dividing by 100.0 you might end up with 3333.8899999999999 instead of 3333.89.
If you only care about DISPLAYING two digits, look at using the "java.text.DecimalFormat" class where you can specify exactly how a real number should be displayed.
 
Nijeesh Balan
Ranch Hand
Posts: 116
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply..
I tried using DecimalFormat("#.00")
it rounds off as well..
any other suggestions?
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think if you use the first method I suggested (multiply by 100.0, assign to an int or long, then divide by 100.0), and then print the new value out as a DecimalFormat that you won't get the rounding.

[ September 17, 2003: Message edited by: Wayne L Johnson ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic