我有很多Java替身。为了在图形用户界面上正确显示,它们的长度只能是7个字符,包括-negative符号和.period
所以我们假设是这样的:
12345.7890
1.34567890
-23.567890我想要
12345.7
1.34567
-23.567在极少数情况下,它会在小数点前超过7个字符,只需保留一位小数即可。四舍五入的优先选择。
我并不精通Java中所有的字符串/双精度操作来有效地完成这项工作。
发布于 2013-03-05 15:20:37
试一试
double d = -23.5678900;
int precision = d < 0 ? 5 : 6;
BigDecimal bd = new BigDecimal(d, new MathContext(precision));它还提供四舍五入。也许添加一个溢出检查是有意义的
if (d > 9999999 | d < -999999) {
System.out.println("#######");
} 发布于 2013-03-05 15:25:16
如果您只想显示,请使用此方法...
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
}发布于 2013-03-05 16:32:12
标准的方法是使用DecimalFormat
Double d = 12345.7890d;
NumberFormat decimalFormat = new DecimalFormat("-#####.##");
System.out.println(decimalFormat.format(d));https://stackoverflow.com/questions/15217759
复制相似问题