Remove trailing zeros from double

为君一笑 提交于 2019-12-01 03:57:48

If you are willing to switch to BigDecimal, there is a #stripTrailingZeroes() method that accomplishes this.

You can use String manipulation to remove trailing zeros.

private static String removeTrailingZeros(double d) {
  return String.valueOf(d).replaceAll("[0]*$", "").replaceAll(".$", "");
}

System.out.println(removeTrailingZeros(1234.23432400000));
System.out.println(removeTrailingZeros(12.0));

private static String removeTrailingZeros(double d) {
return String.valueOf(d).replaceAll("[0]*$", "").replaceAll(".$", "");
}

or

private static String removeTrailingZeros(double d) {
return String.valueOf(d).replaceAll(".?0*$", "");
}

These are wrong code.

System.out.println(removeTrailingZeros(1234.23432400000));
return: 1234.23432
but must return: 1234.234324


private static String removeTrailingZeros(double myDouble) {
return (new BigDecimal(Double.toString(myDouble))).toPlainString().replaceAll("[0]
*$", "").replaceAll(".$", "");
}

This method is working wrong too

System.out.println(removeTrailingZeros(472.304000)); returns 472.30 instead of 472.304

System.out.println(removeTrailingZeros(472304000)); returns 47230 instead of 472304000


The #stripTrailingZeroes() or toPlainString() of the BigDecimal are good method, but nor alone.

//----------------BigDecimal.toPlainString-------------
System.out.println((new BigDecimal(Double.toString(4724))).toPlainString());
System.out.println((new BigDecimal(Double.toString(472304000))).toPlainString());

returns:
4724.0 (this is not fine - we don't want '.0')
472304000 (This is fine)

//----------------BigDecimal.stripTrailingZeros-------------
System.out.println((new BigDecimal(Double.toString(4724)).stripTrailingZeros()));
System.out.println((new BigDecimal(Double.toString(472304000d)).stripTrailingZeros()));

returns:
4724.0 (This is fine)
4.72304E+8 (This is not fine - we want 472304000)

The perfect resolution of the currect subject "Remove trailing zeros from double" is using
.stripTrailingZeros().toPlainString()

For example :
//---------BigDecimal.stripTrailingZeros.toPlainString-----------------
System.out.println(new BigDecimal(Double.toString(472.304000)).stripTrailingZeros().toPlainString());
System.out.println((new BigDecimal(Double.toString(4724)).stripTrailingZeros().toPlainString()));
System.out.println((new BigDecimal(Double.toString(472304000d)).stripTrailingZeros().toPlainString()));

Result is:
472.304 (correct)
4724 (correct)
472304000 (correct)

double result = ...;
int intResult = (int)result;
if (result == intResult) {
    System.out.println(intResult);
} else {
    System.out.println(result);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!