Java String Formatting Java This example shows how to specify precision with String#printf() Precision is only applied to strings (limiting chars) or floating points (limiting decimal places) Syntax: x.y; where x= padding (width) and y= number of chars. For floating point numbers y is used for decimal places. If the precision is not specified then there is no explicit limit on the number of characters. package com.logicbig.example.string;
public class StringPrintfPrecision {
public static void main(String[] args) { //limit to 8 chars System.out.printf("%.8s%n", "Welcome to my World!"); //limit to 6 chars with 15 left spaces (padding) System.out.printf("[%15.6s]%n", "Where are you going?"); //limit to 6 chars with 15 right spaces (padding) System.out.printf("[%-15.6s]%n", "Where are you going?"); //floating point precision of 6 with left padding 10 System.out.printf("[%10.6f]%n", Math.PI); //floating point precision of 6 with left padding 10 System.out.printf("[%10.2d]%n", 543235999); } }
OutputWelcome [ Where ] [Where ] [ 3.141593] [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project java-string: An exception occured while executing the Java class. 2 -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
|