0

I'd like to convert miles to kilometers. Is usage of BigDecimal an overkill in this situation?

Could I improved the following not using BigDecimals? I'd like to round to the nearest full number. I'm not interested in the decimal fractions.

private static final BigDecimal MILE = new BigDecimal(1.609344);

String milesToKm(String miles) {
    return new BigDecimal(miles).multiply(MILE).setScale(0, RoundingMode.HALF_UP).toString();
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 1
    If you use integers for both kilometers and miles, `BigDecimal` is definitely overkill. I wouldn't know the impact though (you could measure the time difference). The floating point errors are extremely small, so you won't notice them if you round after converting. (I don't have references to prove my statements - although I'm sure they exist - that's why I won't post this as an answer ;-) ) – Vincent van der Weele Nov 21 '13 at 16:17
  • as `MILE` must be a decimal with fractions, I probably cannot use BigInteger here... – membersound Nov 21 '13 at 16:20
  • I was hinting at simply using `double` or `float`... – Vincent van der Weele Nov 21 '13 at 16:37

1 Answers1

2

Whats wrong with just using double?

int km = (int) Math.round(miles * 1.609344D);

Why worry about miniscule accuray errors if you're rounding to integer anyway?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Durandal
  • 19,919
  • 4
  • 36
  • 70