java - JOptionPane 输出双至 2 位小数:
问题描述
所以我已经完成了另一个课程计划,并试图让它看起来更“好”一点。我对每个问题和选择都使用了 JOptionPane,但输出...有没有办法使用 J-pane 将答案输出到 System.ou.print 的小数点后 2 位?
只发布一种方法的部分代码
public static void Celsius()
//First method used within Start to convert Celsius to Fahrenheit
{
double converted;
double temperature;
//user inputs temperature to be converted
temperature = Double.parseDouble(JOptionPane.showInputDialog(null,
"Please enter the temperature in Celsius and press 'Ok'",
"You selected Celsius to Fahrenheit",
JOptionPane.INFORMATION_MESSAGE));
converted = 9/5.0*temperature+32;
//outputs converted temperature
System.out.print("The converted temperature in Fahrenheit = ");
System.out.printf(" %.2f", converted);
System.out.println(" degrees Fahrenheit");
}
解决方案
您正在寻找DecimalFormat(另请参阅此处)
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.456345);
JOptionPane.showMessageDialog(null, "Result: " + formatted); // shows 2.46
推荐阅读
- javascript - 计算平均值时如何从数组中排除零值?
- javascript - 从 Javascript 强制“空缓存和硬重新加载”
- javascript - 在编写游戏时,如何防止脚本通过点击事件 jQuery 分配?
- string - How can I draw a UML class that must be a valid IP address
- php - 为什么我的 Laravel 应用程序将 html 标签输出为字符串
- google-maps - 如何在点击谷歌地图时改变多边形的边缘
- android-studio - Android 项目包含以“._”开头的额外文件
- html - 如何计算自定义 ValidityState
- c++ - How to group decimal places as well?
- hive - 为什么在 Hive 中映射器的数量变化如此之大以进行插入覆盖