Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Restricting the number of floating point digits

 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I just wanted to know how to restrict the number of floating point digits of a float value. I mean after the decimal point after have only 3 digits. like 20.111(only three 1s).
Thank you very much.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you want to restrict this precision for display or calculation purposes?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might consider not using floats. Use long or int to store the real number * 1000. Format the decimal places only for display. This is one way to make sure the 3-digit fractional part multplies, divides and rounds the way you'd expect. It might be fun to make your own number class that uses float for all input and output but hides ints internally.
 
Preetham Chandrasekhar
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NumberFormat class has methods like setMaximumFractionDigits...

for example:

double d = 23.2323;
Numberformat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(2);
String snum = number.format(d);
d = Double.parseDouble(snum);
// this would return 23.23

I know this is a bit complicated but it does what u need

Preetham
SCJP 1.4
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic