What happened to printf or how do I format the numbers I need to print?

John Zukowski

The Java libraries and println() method provide no direct equivalent to printf/sprintf. While Acme labs provides an alternative at http://www.acme.com/java/software/Acme.Fmt.html, the NumberFormat class provides a mechanism for setting the number of characters to display before and after the decimal point.

For instance, the following would print out a number with commas for the thousand, millions, billions, etc, at least one number after the decimal point, and at most two numbers (w/o rounding) after the decimal point.

NumberFormat format  = new DecimalFormat("#,##0.0#");
System.out.println(format.format(0));
System.out.println(format.format(10000));
System.out.println(format.format(100000000));
System.out.println(format.format(25.25));
System.out.println(format.format(-10.125));

Running this would display:

0.0
10,000.0
100,000,000.0
25.25
-10.12

For additional formatting options, see the description of the DecimalFormat class.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact