gpt4 book ai didi

Java:如何设置 Double 的最大长度?

转载 作者:行者123 更新时间:2023-12-01 22:04:52 26 4
gpt4 key购买 nike

如何设置 double 的最大长度?

double divSum = number1 / number2;  
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";

JLabel divSumLabel= new JLabel();
divSumLabel.setText(divDisplay)

如何设置 divSum 的最大长度?

1/3 = 0.333333... 如何设置最大长度,使其仅为 0.333

我可以做:
int maxLenght = 3;

String stringDivSum = String.valueOf(divSum);
String shortDivSum = null;
if(stringDivSum.length() > maxLenght){
shortDivSum = stringDivSum.substring(0, maxLenght);
}

String divDisplay = number1 + "/"+ number2 + "= "+ ShortDivSum + "";
但是当我执行 1/3 时,它会打印出 1/3 = 0.3

最佳答案

Use String.format(...)

String.format()

double divSum = Double.parseDouble(String.format("%.3f",(double)number1  /  number2)) ;

double 。

We can specify the precision of a double or float. We use the "f" to indicate a floating-point. Before this we specify ".3" to mean "three numbers after the decimal."

关于Java:如何设置 Double 的最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009177/

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