Rounding float/decimal to 3 decimal places exactly?
You appear to want to round down to FOUR decimal places instead of rounding half up.
double d = 0.08095238095238096;
d = (long) (d * 10000) / 10000.0;
or
d = Math.floor(d * 10000) / 10000.0;
I assume you mean you want d = 0.0809 instead of 0.809.
Perhaps you are thinking of 3 significant digits which is a harder problem.
Its best to use double
or BigDecimal
instead of float
unless you have a very good reason.
BTW: It is useful to have a clear idea of what you want, otherwise its going to be much harder to find it. ;)
Lunar
Updated on June 04, 2022Comments
-
Lunar almost 2 years
I know there are many questions asking for this, but I have tried quite a few of the solutions but none seem to work exactly how I need it!
Most solutions work, however in my test data I have the
float
:0.08095238095238096
If I round this to 4 I seem to get;
0.081
when I need to have0.0809
and not rounded up that last place.Also am I best using float or double for this type of number?
Thanks
-
Bohemian over 12 yearsYour problem is your original number is wrong. If you need to get
0.809
you'll need to start with0.8095238095238096
(not0.08095238095238096
as you have). -
tchrist over 11 yearspossible duplicate of Round a double to 2 significant figures after decimal point
-