好吧,我知道這裏有一個很相似的問題,但它並沒有完全回答我的問題。請讓我知道我是否做錯了。打印前3位小數無四捨五入
我已經寫了一個程序,從用戶獲取華氏溫度並將其轉換爲Celcius。它看起來像這樣:
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");
}
}
當它打印答案時,我只想打印前3個小數位,但不是圓形。例如,如果輸入爲100F
,我想要37.777C
印刷,而不是37.778C
。
我試過使用DecimalFormat
和String.format
(如上),但兩種方法打印出37.778C
。有一個更好的方法嗎?
謝謝你的回答,如果這是重複的,我很抱歉。
謝謝你的編輯,約翰。 –