简体   繁体   中英

Formatting Dollar Value with DecimalFormat

I need to display a dollar value with the following requirements.

  1. If the value is less than a dollar, place a leading zero. eg 0.55
  2. If the value has no cents, place two trailing zeros. eg 100.00
  3. Here's the tricky part. The value may be less than a cent, in which case it should be printed as-is. eg 0.005

Is it possible to implement this 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM