简体   繁体   English

使用printf在Java中显示两位小数?

[英]Display two decimal places in java using printf?

A sample of the code below 下面的代码示例

double maxHeight;
maxHeight = (Math.pow(speed * Math.sin(angle), 2) / 2 * gravity);
System.out.printf("Maximum height: %.2f", (maxHeight));

The error i receive: 我收到的错误:

"The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, double)" “类型为PrintStream的方法printf(String,Object [])不适用于参数(字符串,双精度)”

What is the simplest solution to printing only two decimal places using printf method or are there any other solutions without creating a decimalFormat? 使用printf方法仅打印两位小数的最简单解决方案是什么?或者是否有其他解决方案却不创建decimalFormat?

The problem is that varargs is looking for one or more Object s, and you provided a primitive variable. 问题在于varargs正在寻找一个或多个Object ,并且您提供了一个原始变量。 The simplest method is probably just to wrap it: 最简单的方法可能只是包装它:

System.out.printf("Maximum height: %.2f", Double.valueOf(maxHeight));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM