Rounding float/decimal to 3 decimal places exactly?

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 have 0.0809 and not rounded up that last place.

Also am I best using float or double for this type of number?

Thanks

Answers


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. ;)


Need Your Help

Elements affected JavaScript equivalent

javascript dom-manipulation

I would like a JavaScript solution for measuring the number of affected DOM nodes in a period of time.

Groovy sql import error. Can not find property even though it's included

java sql groovy gradle classpath

When trying to run my program from the command line (works in intellij), i receive the following error:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.