Your better solution is using the DecimalFormat class. You can provide a patter which will only show non-zero digits, and there is a flag you can set to make sure the decimal point doesn't get shown in integer-cases.
Hmmm. I got this setRoundingMode method. However, I am required to write this logic in Java 1.4 version, but I could find this method newly added only from version Java 1.6. Is there any other alternative for it?
I was thinking of using BigDecimal in combination with its stripTrailingZeros() method, which preserves 3.245 as 3.245. However, you've guessed it - the method has been created after Java 1.4.
That said, it shouldn't be too hard using simple String manipulation:
1) find the index of . - if it's not present, then you're done
2) from the end, check each character if it's 0. If it isn't go to step 3. Stop if you've reached the .
3) create a substring until the last non-0 character
You can possibly combine steps 1 and 2 into one for a single loop.
zahid zubair wrote:Hmmm. I got this setRoundingMode method. However, I am required to write this logic in Java 1.4 version, but I could find this method newly added only from version Java 1.6. Is there any other alternative for it?
That stinks. Why are you stuck with Java 1.4? It has been at End of Life for some time? Shouldn't you think about updating to a supported version of Java?
Anyway, in Java 1.4 DecimalFormat always rounded towards the even number for xxx5. So if it was 2.015 it would round to 2.02 and if it was 2.025 it would round to 2.02 which I think is used because it more evenly disperses rounded values. the only way I know how to make sure it always makes half-values round up would be to use BigDecimal and set the scale.