我有很多 Java 双打。为了在 GUI 上正确显示,它们只能是 7 个字符长,包括 -negative sign 和 .period
所以让我们说它就像:
12345.7890
1.34567890
-23.567890
我想
12345.7
1.34567
-23.567
在极少数情况下,它在小数点前超过 7 个字符,只需保留 1 个小数位。适当舍入的首选。
我并不精通 Java 中的所有字符串/双精度操作来有效地做到这一点。
try
double d = -23.5678900;
int precision = d < 0 ? 5 : 6;
BigDecimal bd = new BigDecimal(d, new MathContext(precision));
it also provides rounding. Maybe it makes sense to add a check for overflow
if (d > 9999999 | d < -999999) {
System.out.println("#######");
}
那么标准的方法是使用DecimalFormat
Double d = 12345.7890d;
NumberFormat decimalFormat = new DecimalFormat("-#####.##");
System.out.println(decimalFormat.format(d));
如果您只想用于显示目的,请使用此方法...
Double d = -1.151266662625;
String str = d.toString();
String result = Str.substring(0,7);
if(result.contains("."){
// it is according to your need
}else{
// iF dot is not present do what ever you want to do. Either again truncte the string upto 5 place and add ".0" in end of the string
}