Sunday, April 7, 2013

Java DecimalFormat example


Sites to launch java code online:
http://www.compileonline.com/compile_java_online.php
http://www.javalaunch.com/JavaLaunch.jsp (no restrictions)
http://rextester.com/runcode (attention: it restrict class to be named as Rextester) list of all, here .

Task: Print 0.1278 as 12.8%. java doc.

 Code:
import java.text.DecimalFormat;

public class Test {

 static public void customFormat(String pattern, double value) {
  DecimalFormat myFormatter = new DecimalFormat(pattern);
  String output = myFormatter.format(value);
  System.out.println(value + "  " + pattern + "  " + output);
 }

 static public void main(String[] args) {
  customFormat("000.0%", 0.1278);
  customFormat("#0.00%", 0.1278);
  customFormat("###.##%", 0.1278);
  customFormat("##0.0%", 0.1278); ////!!!!!
  customFormat("#.####%", 0.1278);
 }

}

No comments:

Post a Comment