I need to display a dollar value with the following requirements.
- If the value is less than a dollar, place a leading zero. e.g 0.55
- If the value has no cents, place two trailing zeros. e.g. 100.00
- Here's the tricky part. The value may be less than a cent, in which case it should be printed as-is. e.g 0.005
Is it possible to implement 开发者_如何学JAVAthis with DecimalFormat
? If it wasn't for the last requirement, a pattern of "0.00" would do, but I'm not sure how to do the last.
You could try an if statement and redeclare your DecimalFormat:
if(num < 0.01 && num != 0)
DecimalFormat dec = new DecimalFormat("$#,##0.000");
That's pretty brute force though, don't know if there's any pattern in DecimalFormat to change it directly.
I figured it out, well sort of. For this to work, you need to know the maximum count of decimal digits. For my needs, the value can have up to 3 decimal digits, so a pattern of "0.00#" did the trick.
精彩评论