【发布时间】:2015-08-31 02:23:48
【问题描述】:
好的,我知道已经有一个非常相似的问题,但它并没有完全回答我的问题。如果我做错了什么,请告诉我。
我编写了一个程序,从用户那里获取华氏温度并将其转换为摄氏度。它看起来像这样:
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。有没有更好的方法来做到这一点?
感谢您的回答,如有重复,我深表歉意。
【问题讨论】:
-
感谢您的编辑,约翰。
标签: java floating-point rounding