vector
vector

Reputation: 7576

accurately representing time in java and groovy

I need to do calculations on units of time represented in whole and/or tenths of an hour and wonder if BigDecimal is the appropriate datatype for it. From what I gather BigDecimal would be appropriate for currency calculations so am I thinking the same is true in cases where I have to deal with 1.5 + 0.6 type of simple math. Is my thinking correct here?

Upvotes: 1

Views: 114

Answers (2)

Michael D Johnson
Michael D Johnson

Reputation: 929

The short answer is yes. If you are performing decimal calculations then BigDecimal is a good class to use to avoid any kind of rounding errors. However, it's probably not the most efficient way. If performance is not an issue then I would say that BigDecimal will serve your purpose.

An alternative would be to perform your calculations in minutes and then divide your answer by 6 to provide the result. In that case you could use an Integer and hold off on the expensive calculation until the end. When you divide by 6 you could cast your answer into a double.

Double answer = 154 / 6.0 //154 represents calculated minutes

Upvotes: 1

dvberkel
dvberkel

Reputation: 663

Because you question mentions that you only need to work with tenths of an hour, it is base you representation on multiples of this smallest time unit, i.e. 6 minutes.

This way it is possible to represent time with an integer data type like, Integer or BigInteger, depending on the maximum time to represent.

You could even write a custom class which wraps the (Big)Integer and provides methods for formatting to string, conversion between other types, etcetera.

Upvotes: 0

Related Questions