gpt4 book ai didi

java - 打印前 3 位小数而不四舍五入

转载 作者:搜寻专家 更新时间:2023-11-01 01:04:49 25 4
gpt4 key购买 nike

好的,我知道已经有一个非常相似的问题,但它并没有完全回答我的问题。如果我做错了什么,请告诉我。

我编写了一个程序,从用户那里获取华氏温度并将其转换为摄氏温度。它看起来像这样:

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

我尝试过使用 DecimalFormatString.format(如上),但这两种方法都打印出 37.778C。有更好的方法吗?

感谢您的回答,如果重复,我深表歉意。

最佳答案

您可以使用DecimalFormat,只需设置RoundingMode :

DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);

关于java - 打印前 3 位小数而不四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com