This week's giveaway is in the Spring forum.We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!

# Restricting the number of floating point digits

Ransika deSilva
Ranch Hand
Posts: 524
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
Do you want to restrict this precision for display or calculation purposes?

Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
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
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