I would like to remove all trailing zeros without truncating or rounding the number if it doesn't have any. For example, the number could be something like 12.0
, in which case, the trailing zero should be removed. But the number could also be something almost irrational, like 12.9845927346958762...
going on an on to the edge of the screen. Is there a way to setup DecimalFormat or some other class to cut of trailing zeros, while keeping the irrationality intact?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can use String manipulation to remove trailing zeros.
If you are willing to switch to
BigDecimal
, there is a #stripTrailingZeroes() method that accomplishes this.or
These are wrong code.
This method is working wrong too
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)