Calculate Miles per Gallon to Kilometers per Litre in Java


The challenge

Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input).

Make sure to round off the result to two decimal points. If the answer ends with a 0, it should be rounded off without the 0. So instead of 5.50, we should get 5.5.

Some useful associations relevant to this challenge:

1 Imperial Gallon = 4.54609188 litres

1 Mile = 1.609344 kilometres

The solution in Java code

Option 1:

public class Converter {
  public static float mpgToKPM(final float mpg) {
    float gallon = 4.54609188f; //lts
    float mile = 1.609344f; // kms
    
    float out = (mpg*mile)/gallon;
    
    return (float) Math.round(out*100)/100;
  }
}

Option 2:

public class Converter {

  private static final float LITER = 4.54609188f;
  private static final float KILOMETER = 1.609344f;
  
  public static float mpgToKPM(final float mpg) {
    return Float.parseFloat(String.format("%.2f", mpg * KILOMETER / LITER ));
  }
}

Option 3:

public class Converter {
    public static float mpgToKPM(final float mpg) {
        return Math.round(mpg * 35.4006044) / 100f;
    }
}

Test cases to validate our solution

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.Random;
import java.math.BigDecimal;

public class TestConverter {

  private static int NUM_RANDOM_TESTS = 40;
  private static int MAX_MPG = 5000;
  private static float KM_PER_MILE = 1.609344f;
  private static float LITRES_PER_GALLON = 4.54609188f;


  @Test
  public void test1() {
    assertEquals(3.54f, Converter.mpgToKPM(10), 0.001f);
  }
  
  @Test
  public void test2() {
    assertEquals(7.08f, Converter.mpgToKPM(20), 0.001f);
  }
  
  @Test
  public void test3() {
    assertEquals(10.62f, Converter.mpgToKPM(30), 0.001f);
  }
  
  @Test
  public void test4() {
    assertEquals(8.50f, Converter.mpgToKPM(24), 0.001f);
  }
  
  @Test
  public void test5() {
    assertEquals(12.74f, Converter.mpgToKPM(36), 0.001f);
  }
  
  @Test
  public void testRandoms() {
    Random random = new Random();
    for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
      int mpg = random.nextInt(MAX_MPG);
      assertEquals("Testing where MPG = " + mpg, solution(mpg), Converter.mpgToKPM(mpg), 0.001f);
    }
  }
  
  private float solution(final float mpg) {
    return new BigDecimal(mpg * KM_PER_MILE / LITRES_PER_GALLON).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue();
  }
}