Last active
April 13, 2020 10:02
-
-
Save tkuenneth/a37d2065c0a09941eab332a5f0d8c59a to your computer and use it in GitHub Desktop.
Temperature conversions written in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.thomaskuenneth.temperatureconverter; | |
import java.text.DecimalFormat; | |
import java.text.NumberFormat; | |
import java.text.ParseException; | |
public class Converter { | |
public static final String DEGREES_CELSIUS = "\u00B0C"; | |
public static final String DEGREES_FAHRENHEIT = "\u00B0F"; | |
public static final String KELVIN = "K"; | |
public static double stringToDouble(String s) throws ParseException { | |
NumberFormat df = DecimalFormat.getInstance(); | |
Number n = df.parse(s); | |
return n.doubleValue(); | |
} | |
public static double celsiusToKelvin(double celsius) { | |
return 273.15 + celsius; | |
} | |
public static double fahrenheitToKelvin(double fahrenheit) { | |
return (fahrenheit + 459.67) * 5f / 9f; | |
} | |
public static double kelvinToCelsius(double kelvin) { | |
return kelvin - 273.15; | |
} | |
public static double kelvinToFahrenheit(double kelvin) { | |
return kelvin * 1.8 - 459.67; | |
} | |
public static double celsiusToFahrenheit(double celsius) { | |
return (celsius * 1.8) + 32.0; | |
} | |
public static double fahrenheitToCelsius(double fahrenheit) { | |
return (fahrenheit - 32) * (5.0 / 9.0); | |
} | |
public static String celsiusToString(double celsius) { | |
return doubleToString(celsius, DEGREES_CELSIUS); | |
} | |
public static String fahrenheitToString(double fahrenheit) { | |
return doubleToString(fahrenheit, DEGREES_FAHRENHEIT); | |
} | |
public static String kelvinToString(double kelvin) { | |
return doubleToString(kelvin, KELVIN); | |
} | |
private static String doubleToString(double val, String suffix) { | |
return String.format("%s %s", | |
(val == (long) val) | |
? String.format("%d", (long) val) | |
: String.format("%.2f", val), suffix); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment