Okay, I know there is a question quite similar already, but it didn't quite answer my question. Please let me know if I'm doing something wrong though.
I have written a program that gets a temperature in Fahrenheit from the user and converts it to Celcius. It looks like this:
import java.util.Scanner;
public class FahrenheitToCelcius {
public static void main(String[] args) {
double fahrenheit;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a temperature in Fahrenheit: ");
fahrenheit = sc.nextDouble();
double celcius = (fahrenheit - 32) * 5 / 9;
String num = String.format("%.3f", celcius);
System.out.println(" ");
System.out.println(fahrenheit + "F" + " is " + num + "C");
}
}
When it prints the answer out, I want only the first 3 decimal places printed, but not rounded. For example, if the input is 100F
, I want 37.777C
printed, not 37.778C
.
I have tried using DecimalFormat
and String.format
(like above), but both methods print out 37.778C
. Is there a better way to do this?
Thank you for your answers, and I apologise if this is a duplicate.
You can use DecimalFormat
, just set the RoundingMode
:
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);
Multiply celsius by 1000 to move the decimal over 3 spots
celsius = celsius * 1000;
Now floor the number and divide by 1000
celsius = Math.floor(celsius) / 1000;
It will remove the need for the String.format() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With