打印前 3 位小数而不四舍五入
Printing first 3 decimal places without rounding
好的,我知道已经有一个非常相似的问题,但它并没有完全回答我的问题。不过,如果我做错了什么,请告诉我。
我编写了一个程序,可以从用户那里获取华氏温度并将其转换为摄氏温度。它看起来像这样:
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
。有更好的方法吗?
感谢您的回答,如果重复,我深表歉意。
您可以使用DecimalFormat
,只需设置RoundingMode
:
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);
摄氏度乘以 1000 将小数点移动 3 位
celsius = celsius * 1000;
现在将数字减去 1000
celsius = Math.floor(celsius) / 1000;
它将不再需要 String.format() 方法。
这个答案类似于使用 Math.floor 但可能更容易转换为 int:
想要小数点后两位?试试这个:
System.out.println( (int) (your_double * 100) / 100.0 );
想要 3 位小数?试试这个:
System.out.println( (int) (your_double * 1000) / 1000.0 );
想要 4 位小数?试试这个:
System.out.println( (int) (your_double * 10000) / 10000.0 );
看到规律了吗?将你的双倍数乘以 10 到你想要的小数位数的幂。转换后,除以附加小数零。
您可以简单地四舍五入到小数点后 4 位,然后 trim 最后一个字符。
String num = String.format("%.4f", celcius);
num = num.substring(0, num.length() - 1);
好的,我知道已经有一个非常相似的问题,但它并没有完全回答我的问题。不过,如果我做错了什么,请告诉我。
我编写了一个程序,可以从用户那里获取华氏温度并将其转换为摄氏温度。它看起来像这样:
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
。有更好的方法吗?
感谢您的回答,如果重复,我深表歉意。
您可以使用DecimalFormat
,只需设置RoundingMode
:
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);
摄氏度乘以 1000 将小数点移动 3 位
celsius = celsius * 1000;
现在将数字减去 1000
celsius = Math.floor(celsius) / 1000;
它将不再需要 String.format() 方法。
这个答案类似于使用 Math.floor 但可能更容易转换为 int:
想要小数点后两位?试试这个:
System.out.println( (int) (your_double * 100) / 100.0 );
想要 3 位小数?试试这个:
System.out.println( (int) (your_double * 1000) / 1000.0 );
想要 4 位小数?试试这个:
System.out.println( (int) (your_double * 10000) / 10000.0 );
看到规律了吗?将你的双倍数乘以 10 到你想要的小数位数的幂。转换后,除以附加小数零。
您可以简单地四舍五入到小数点后 4 位,然后 trim 最后一个字符。
String num = String.format("%.4f", celcius);
num = num.substring(0, num.length() - 1);