我怎样才能改变一个
Double d = 2.3
到
Double with value of 2.0
我用过Math.round
,但它会产生2.0
我需要将其保存String
为2.0
我怎样才能改变一个
Double d = 2.3
到
Double with value of 2.0
我用过Math.round
,但它会产生2.0
我需要将其保存String
为2.0
您可以使用printf(...)
:
System.out.printf("Double with value of %.1f", Math.round(d));
或者您可以使用以下方法将其保存到字符串String.format(...)
:
String s = String.format("Double with value of %1f", Math.round(d));
如果您需要将数值更改为您使用的字符串:
String.valueOf(myDouble);
如果您使用Double包装器来存储您的双精度值,您也可以使用它:
myDouble.toString();
所以你可以将它与你的 Math.round() 调用结合使用。
感谢@Hunter,我能够通过以下方式做到这一点
String.valueOf(new Double(Math.round(new Double(Double.parseDouble(minorVersion) + 1.0))));
最简单的代码:
String s = "" + myDouble;
您问题的基本答案是使用
String.valueOf(doubleNo) //in your case doubleNo is 2.0 after rounding
但是,考虑使用 BigDecimal 而不是使用 double,在这种情况下,您可以使用以下方法
public String roundAndPrintDouble(double no){
String numberAsString = String.valueOf(no);
BigDecimal decimalNo = new BigDecimal(numberAsString);
BigDecimal roundedDecimal = decimalNo.round(MathContext.DECIMAL128);
return roundedDecimal.toPlainString();
}
如果您使用此解决方案的可能性不大,请查看 JavaDocs for BigDecimal和MathContext之前。