<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>good practice &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/good-practice/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Wed, 18 May 2022 15:57:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How To Turn Number To String With Padded Space or Zeroes</title>
		<link>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/</link>
					<comments>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Apr 2022 14:59:52 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[Formatter]]></category>
		<category><![CDATA[good practice]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1293</guid>

					<description><![CDATA[Article about a simple solution to turning numbers into specific length <em>String</em> with padded space. <a href="https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show us how to turn numbers into the <em>String</em> with padded space or numbers.</p>
<p><span id="more-1293"></span></p>
<h2>Introduction</h2>
<p>I have been recently doing code review on other developer pull-request when I found the piece of code below:</p>
<pre><code class="language-java">private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    String documentVersion = "";
    if (version > 999) {
        throw new IllegalStateException("Version number " + version + " is too large.");
    } else if (version > 99) {
        documentVersion += version;
    } else if (version > 9) {
        documentVersion += "0" + version;
    } else {
        documentVersion += "00" + version;
    }

    return "DOCUMENT_VERSION_" + documentVersion;
}</code></pre>
<p>As you can immediately see, the code is bad and can be surely rewritten to something more simple. Creating a string from a number can not be so declarative, right? There needs to be a simpler way how to do it. And surely it can. Like many other general-purpose programming languages, Java has multiple libraries and functions for processing text. <em>String</em> class itself has a static method <em>format()</em> which can be fully utilized on the text changes like this.</p>
<h2>Java String format()</h2>
<p>The Java <em>String</em> class <em>format()</em> method returns the formatted string. Let&#8217;s look little bit on parameters of <em>format()</em> method.</p>
<h3>String.format() signature</h3>
<p>There are two type of <em>String format()</em> method:</p>
<pre><code class="language-java">public static String format(String format, Object... args)</code></pre>
<p>and</p>
<pre><code class="language-java">public static String format(Locale locale, String format, Object... args)  </code></pre>
<p>Therefore, method parameters are described as:</p>
<ul>
<li><b>locale</b> is specifies the locale to be applied on the format() method.</li>
<li><b>format</b> is format of the string.</li>
<li><b>args</b> represent arguments for the format string. It may be zero or more.</li>
</ul>
<p><em>format()</em> method returns new <em>String</em>. However, it is also good to be prepared for possibility of two unchecked exception:</p>
<ul>
<li><b>NullPointerException</b> is thrown if <b>format</b> is null.</li>
<li><b>IllegalFormatException</b> is thrown if <b>format</b> is illegal or incompatible.</li>
</ul>
<h3>String.format() internal implementation</h3>
<p>In reality, <em>String.format()</em> method allows usage of multiple <em>Object</em> arguments because internal implementation use nothing else than new instance of <em><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html" title="Java 8 Docs - Formatter Class" target="_blank" rel="nofollow noopener">Formatter</a></em> class.</p>
<pre><code class="language-java">public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}</code></pre>
<p>Usage of quiet <em>Formatter</em> class explains why we can take multiple arguments depending on the number of elements we want to format inside the string. <em>Formatter</em> class can use several different option of &#8220;%&#8221; character combination in order to define string formatting. In the table below are all options explained:</p>
<table>
<thead>
<tr>
<th>Formatter Argument</th>
<th>Data Type</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>%a %A</td>
<td>floating point (except BigDecimal)</td>
<td>Returns Hex output of floating point number.</td>
</tr>
<tr>
<td>%b</td>
<td>Any type</td>
<td>&#8220;true&#8221; if non-null, &#8220;false&#8221; if null</td>
</tr>
<tr>
<td>%c</td>
<td>character</td>
<td>Unicode character</td>
</tr>
<tr>
<td>%d</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Decimal Integer</td>
</tr>
<tr>
<td>%e</td>
<td>floating point</td>
<td>decimal number in scientific notation</td>
</tr>
<tr>
<td>%f</td>
<td>floating point</td>
<td>decimal number</td>
</tr>
<tr>
<td>%g</td>
<td>floating point</td>
<td>decimal number, possibly in scientific notation depending on the precision and value.</td>
</tr>
<tr>
<td>%h</td>
<td>any type</td>
<td>Hex String of value from hashCode() method.</td>
</tr>
<tr>
<td>%n</td>
<td>none</td>
<td>Platform-specific line separator.</td>
</tr>
<tr>
<td>%o</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Octal number</td>
</tr>
<tr>
<td>%s</td>
<td>any type</td>
<td>String value</td>
</tr>
<tr>
<td>%t</td>
<td>Date/Time (incl. long, Calendar, Date and TemporalAccessor)</td>
<td>%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.</td>
</tr>
<tr>
<td>%x</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Hex string.</td>
</tr>
</tbody>
</table>
<h2><em>format()</em> examples</h2>
<p>Let us show you few tricks with <em>format()</em></p>
<pre><code class="language-bash">System.out.println(String.format("%d", 100)); // Integer
System.out.println(String.format("%s", "Anna Smith")); // String
System.out.println(String.format("%f", 42.42)); // Float
System.out.println(String.format("%x", 100)); // Hexadecimal
System.out.println(String.format("%c", 'a')); // Char
System.out.println("-----");
System.out.println(String.format("number with text: %d", 100)); // number with other text
System.out.println(String.format("%f", 42.12345)); // prints floating number
System.out.println(String.format("%10.10f", 42.12345)); // prints 10 digits for fractions padded with 0
System.out.println("-----");
System.out.println(String.format("|<-%10d->|", 222)); // Align right, padding with empty space
System.out.println(String.format("|<-%-10d->|", 555)); // Align left, padding with empty space
System.out.println(String.format("|<-% d->|", 777)); // Single space between % and conversion type is allowed
System.out.println(String.format("|<-%010d->|", 999)); // Filling space with zeros</code></pre>
<pre><code class="language-java">100
Anna Smith
42.420000
64
a
-----
number with text: 100
42.123450
42.1234500000
-----
|<-       222->|
|<-555       ->|
|<- 777->|
|<-0000000999->|</code></pre>
<h2>Using <em>format()</em> to turn number into formatted string</h2>
<p>To take for first exemplary code from code review, all what we needed to do in <code>getDocumentVersion()</code> method was to place custom format of string into the <em>String</em> class <em>format</em> method.</p>
<pre><code class="language-java">private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    return String.format(DOCUMENT_VERSION + "%03d", revisionNumber);
}</code></pre>
<p>If we place number 1 into the method <code>getDocumentVersion()</code> we will get the same result as boilerplate code from code review:</p>
<p><b>Output</b></p>
<pre><code class="language-bash">document_version-001</code></pre>
<p>We can still quickly write some custom code to test our beliefs. But be thorough and do not forget edge cases as zero and negative numbers.</p>
<pre><code class="language-java">System.out.println(String.format("%03d", 999));
System.out.println(String.format("%03d", 99));
System.out.println(String.format("%03d", 9));
System.out.println(String.format("%03d", 0));
System.out.println(String.format("%03d", -9));</code></pre>
<pre><code class="language-java">999
099
009
000
-09</code></pre>
<p>As you can notice <em>format()</em> takes negative number into account its length with minus sign.</p>
<p><b>Note</b> : If you have any crazy idea how to use <em>format()</em> method, let us know in comments below.</p>
<h2>Conclusion</h2>
<p>This article showed us how to turn a number into a string with a specific length where additional space is padded.</p>
<p>Did you find the <em>String.format()</em> method useful? Do you have your trick, or do you know another way <u>how to turn a number into a string of specific length</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
