Search code examples
javabigdecimal

Converting a decimal number to full integer - is BigDecimal overkill?


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();
}

Solution

  • 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?