vrijdag 8 april 2011

[Java] Format a Float @ 2 decimals precision

Here's a small code example of how you could format a float to be displayed at 2 decimals precision (only when necessary).

  1. import java.text.NumberFormat;
  2. ...
  3. NumberFormat nf = NumberFormat.getInstance();
  4. nf.setMaximumFractionDigits(2);
  5. nf.setMinimumFractionDigits(0)

To actually format a float, one could simply do:

  1. nf.format(myFloat);

It's as simple as that ;)

Geen opmerkingen:

Een reactie posten