[英]How can I use String.format() to format doubles in Java
I am trying to format double the same way as this but my Java is giving me an "IllegalFormatPrecisionException".我试图以与此相同的方式格式化 double,但我的 Java 给了我一个“IllegalFormatPrecisionException”。 How do I fix this.
我该如何解决。
public static void main(String[] args) {
double t = 321.4532;
String str = String.format("%.1d", t);
}
%d is used for integer values try using %d 用于整数值尝试使用
public static void main(String[] args) {
double t = 321.4532;
String str = String.format("%.1f", t);
}
Quoting from this [site][1]:引自 [站点][1]:
Don't try to use "d" for double here, because that is used to format integer and stands for decimal in formatting instruction.不要尝试在此处使用“d”表示 double,因为它用于格式化整数并在格式化指令中代表十进制。
Use %.2f and you will be good.使用 %.2f ,你会很好。
[1]: https://www.java67.com/2014/06/how-to-format-float-or-double-number-java-example.html#:~:text=format(%22%25.,float%20data%20type%20in%20Java. [1]:https://www.java67.com/2014/06/how-to-format-float-or-double-number-java-example.html#:~:text=format(%22%25. ,float%20data%20type%20in%20Java。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.