format 1 « Development « Java Data Type Q&A

Java Data Type Q&A
9.Date Time
10.Date Time Format
19.Number Format
Java Data Type Q&A » Development » format 1 

1. Sprintf equivalent in Java

Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf ...

2. Any lightweight templating solutions in Java with support for conditional formatting?

I'm using MessageFormat to format some addresses with a template like this: "{0}\n{1}\n{2}\n{3}, {4} {5}" where

  • 0 = street 1
  • 1 = street 2
  • 2 = street 3
  • 3 = city
  • 4 = state
  • 5 = zip
Most of these ...

3. How do you format a fractional percentage with java.text.MessageFormat

My percentages get truncated by the default java.text.MessageFormat function, how do you format a percentage without losing precision? Example:

String expectedResult = "12.5%";
double fraction = 0.125;

String actualResult = MessageFormat.format("{0,number,percent}", fraction);
assert expectedResult.equals(actualResult) : actualResult ...

4. Retrieving format string from Format object

In Java is there a way to retrieve the format string from a Format object (or any derived classes) In code:

Format f = new DecimalFormat("$0.00");
Is there something I can use to ...

5. Is it better practice to use String.format over string Concatenation in Java?

Is there a perceptable difference between using String.Format and string concatenation in Java? I tend to use String.format but occasionally will slip and use a concat, I was wondering if one was ...

6. String.format with lazy evaluation

I need something similar to String.format(...) method, but with lazy evaluation. This lazyFormat method should return some object whose toString() method would then evaluate the format pattern. I suspect that ...

7. A means of specifying pattern strings that drive parsing and formatting for arbitrary objects?

I'm building a general purpose data translation tool for internal enterprise use, using Java 5. The various departments use differing formats for coordinate information (latitudes/longitudes), and they want to see ...

8. print spaces with String.format()

how I can rewrite this:

for (int i = 0; i < numberOfSpaces; i++) {
    System.out.print(" ");
using String.format()? PS I'm pretty sure that this is possible but the javadoc ...

9. Formatting (for money) with setText(String.valueOf)

In my code there are some calls to a method that set the values of some JTextFields

This works and it is doing what I want but the values look like this ...

10. Automatic Unicode string formatting in Java

I just came across something like this:

String sample = "somejunk+%3cfoobar%3e+morestuff";
Printed out, sample looks like this:
How does that work? U+003c and U+003e are the Unicode codes for the less ...

11. String.format()

"%11.2lf" of C++ is equivalent to ? You guys have any resource that shows the equivalent formats for both Java and C++?

12. Need some help with String.format

I'm trying to find a complete tutorial about formatting strings in java. I need to create a receipt, like this:

Item1    ...

13. Using DecimalFormat--keeping extra zeros

I'm using DecimalFormat to format doubles to 2 decimal places like this:

DecimalFormat dec = new DecimalFormat("#.##");
double rawPercent = ( (double)(count.getCount().intValue()) / 

14. Formatting strings in java

I am reading the serial buffer with readLine() method. The string returned by readLine() is in the format "str1 : str2". In a while loop when I use readLine() number of ...

15. Understanding the $ in Java's format strings

 StringBuilder sb = new StringBuilder();
 // Send all output to the Appendable object sb
 Formatter formatter = new Formatter(sb, Locale.US);

 // Explicit argument indices may be used to re-order output.

16. Java String formatting

I have a property-file with strings inside, formatted in this way: audit events were purged. {0} events were purged, {1} assets were deleted.
Is there a way to bind some values inside ...

17. C++ Equivalent of %ld in Java for String.format()

For instance, "%11.2lf" in C++ becomes "%11.2f" in Java. How about for long format?

18. Named placeholders in string formatting

In Python, when formatting string, I can fill placeholders by name rather than by position, like that:

print "There's an incorrect value '%(value)s' in column # %(column)d" % \
  { 'value': ...

19. How to Java String.format with a variable precision?

I'd like to vary the precision of a double representation in a string I'm formatting based on user input. Right now I'm trying something like:

String foo = String.format("%.*f\n", precision, my_double);
however I ...

20. Dynamically formatting a string

Before I wander off and roll my own I was wondering if anyone knows of a way to do the following sort of thing... Currently I am using MessageFormat to create some ...

21. DecimalFormat for price formatting in java

Is it possible to format price according to rules like this using DecimalFormat in Java: 50000 => 50 000 rub 00 kop

22. Formatting a string in Java using class attributes

I have a class with an attribute and getter method:

public Class MyClass
  private String myValue = "foo";

  public String getMyValue();
I would like to be able to use the value ...

23. Java printf using variable field size?

I'm just trying to convert some C code over to Java and I'm having a little trouble with String.printf. In C, to get a specific width based on a variable, I can ...

24. Output in a table format in Java's System.out

I'm getting results from a database and want to output the data as a table in Java's standard output I've tried using \t but the first column I want is very variable ...

25. string recieve with utf8 format but have problem in java

i want to know how to receive the string from file in java... that file have different language letters... i used UTF-8 format... this can receive some language letters correctly... but Latin letters cant ...

26. Format String become xxx1, xx10 or 1###, 10## etc

I have following numbers : 1, 2, 3, 4, 10 But I want to print those numbers like this:

I have searched in Google. the keyword is number format. But I've got nothing, ...

27. Java method to format String fields

class Person holds personal data Its constructor receives 3 parameters, two Strings representing first and last names and an int representing age

public Person(String firstName, String lastName, int age) 
its method getName ...

28. How to wrap Java String.format()?

Hey everyone, I would like to wrap the String.format() method with in my own Logger class. I can't figure a way how to pass arguments from my method to String.format().

public class ...

29. java.text.DecimalFormat blank when zero?

Is it possible to show blank (empty string) when the number is zero (0)? (strict no zeros at left)

30. USD Currency Formatting in Java

In java, how can I efficiently convert floats like 1234.56 and similar BigDecimals into Strings like $1,234.56 I'm looking for the following: String 12345.67 becomes String $12,345.67
Float and BigDecimal as well. Thanks.

31. difference between system.out.printf and String.format

may i know what is the difference between the two in java? i am reading a book and it can either use both of it to display strings.

32. Is there a way to build a Java String using an SLF4J-style formatting function?

I've heard that using StringBuilder is faster than using string concatenation, but I'm tired of wrestling with StringBuilder objects all of the time. I was recently exposed to the SLF4J ...

33. How to print vertically aligned text

I want to print an output of the following format in a file..

1 Introduction                  ...

34. Using String.format to place objects of different size at certain positions

I have a bunch of data that I need to beautify and output. The current code I'm using is:

String.format("%1s" + "%7d" + "%17d" + "%18d" + "\n", string, int, int, int);
The ...

35. How to avoid null when formatting value

if date is null, freemarker will raise a exception here is a solution
<#if date??>${date?string('yyyy-MM-dd')}</#if>
but this code is ugly,is there any shortcut like ${date!} ?

36. Write x509 certificate into PEM formatted string in java?

Is there some high level way to write an X509Certificate into a PEM formatted string? Currently I'm doing x509cert.encode() to write it into a DER formatted string, then base 64 encoding it ...

37. Format given string value using string format

I have the string format like S PCF=$S($L(VAL)=5:$E(VAL,1,2)" "$E(VAL,3,5),$L(VAL)=6:$E(VAL,1,3)" "$E(VAL,4,6),1:$E(VAL,1,4)" "$E(VAL,5,7)). I want to format the value in above format. What is best i can do. In format 5:$E(VAL,1,2)" "$E(VAL,3,5).. Here ...

38. String format in java?

Input String: 115.0000 Output String should be like: 115.00 i used this code:

i got IllegalArgumentException. What can i do now?

39. String.format() to fill a string?

I need to fill a String to a certain length with dashes, like:

the total length of the string needs to be 9. The prefix "cow" is constant. I'm iterating up to ...

40. String formatting in Java

I've been using python too much lately and I forget if there's a way to do this in Java:

print "I am a %s" % string
I googled, but it's hard to find ...

41. converting a String to UTF8 format

I java code, i am having a string name = "├Ârebro"; // its a swedish character. But when i use this name in web application. i prints some specail character at ...

42. How do we convert a String from PEM to DER format

Have a String being sent from in the below format:

How do i construct a PublicKey Object from this string ? Have tried the below Remove the ...

43. How to format a java string with leading zero?

Here is the String, for example: "Apple", and I would like to add zero to fill in 8 chars. I would like to show the result like this;' "000Apple" How can I do so? ...

44. Formatting Dollar Value with DecimalFormat

I need to display a dollar value with the following requirements.

  1. If the value is less than a dollar, place a leading zero. e.g 0.55
  2. If the value has no cents, place two ...

45. String formatting problem Java

im trying to format this string into a fixed column style but cant get it to work, heres my code, whats up?

System.out.format("%32s%10n%32s%10n%32s%10n", "Voter: " + e.voteNo + "Candidate: " + vote ...

46. How do I format my String to include the needed white space?

I have a String that I want to format in Java. Here is my code:

import java.util.*;
public class Test{

public static void main(String[] args){
  String a = "John     ...

47. decimalformat versus string.format

With string.format introduced in Java 5, is decimalformat now obsolete? I'm having a hard time finding something you can do in decimalformat that you can't do in string.format.

48. Java output formatting for Strings

I was wondering if someone can show me how to use the format method for Java Strings. For instance If I want the width of all my output to be the same For ...

49. Beginner in Java - String format = " | %-"+maxW[j]+"s"; - What does this string do?

I am a noob in Java and I came across the code below and couldn't figure out its function. maxw[] is an array of type int. row[] is an array of ...

50. Cleanest way to format a String

I'm trying to format a phone number which is stored without formatting in a database. Now currently I just use substring and String concatination to form the formatted String but I'm looking ...

51. Convert NSData (in plist format) to Java String

Hey guys, I have a Cocoa application that sends an NSDictionary over the network to various devices. Previously, it only sent to other Macs, so using NSKeyedArchiver to write to an ...

52. java doesn't allow runtime-selectable-width format strings?

I need a way to print a number as hex, as a zero-padded string of width N, where N is selectable at runtime. This doesn't work:

System.out.println(String.format("%*x", 4, 0x123))
because evidently Java doesn't support ...

53. Formatting my String

I need to write currency values like $35.40 (thirty five dollars and forty cents) and after that, i want to write some "****" so at the end it will be: thirty five dollars ...

54. How to left-align strings in their "field" while using String.format() in Java Language?

First of all, thanks in advance for taking your time trying to help me with this lil' issue. I'm using String.format() in Java trying to emulate the printf() control channel available in ...

55. How to add a LineBreak (\n) to a String.format with fixed String as format?

in this code below message is a final String that have a \n inside it, and it doesn't work. message = format = "Blah %d Blah Blah \nBlah Blah %s Blah" interventionSize = ...

56. Problem with converting string encoded in iso format to another string encoded in utf-8

Firstable I want to say that I was trying to google that problem and search for the anwser on stackoverflow and I know that Java stores String as UTF-16. I have ...

57. How to use Java's DecimalFormat for "smart" currency formatting?

I'd like to use Java's DecimalFormat to format doubles like so:

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41
The best I can come up with so far ...

58. Automatically format a measurement into engineering units in Java

I'm trying to find a way to automatically format a measurement and unit into a String in engineering notation. This is a special case of scientific notation, in ...

59. Bug in String.format / Formatter?

Out of curiosity I tried to create a really large string. It turned out that the Formatter class chokes on width specifications exceeding Integer.MAX_VALUE:

// Produces an empty string. (2147483648 ...

60. Formatting String Output in Java

I am trying to format a string in the output differently than the way it is already formatted within my program. It's a pizza ingredient menu and in the bulk of ...

61. Java: Insert a String at a dynamic index position where the index is a formatted string

I have the string format like this :


{a} - index[0], {b2} - index[1],(str} - index[2],{5} - index[3] ...
this could be more than 20K or 25K indexes. Even it goes up ...

62. How to build a formatted string in Java?

I am somewhat new to Java but I dislike the heavy use of string concatenation I'm seeing in my textbook. For example, I'd like to avoid doing this:

String s = "x:"+x+"," y:"+y+", ...

63. unable to format output





The data is not ...

64. Java DecimalFormat returns a "?"

My DecimalFormat is sometimes returning a '?' when trying to format(). Is there an input that would create this scenario? For example: DecimalFormat df = new DecimalFormat("#.####");
df.format(X) --> '?' What could X possibly be? ...

65. StringTemplate Formatting last item in a list

I am generating source using StringTemplate, I need to render a list of statements I want all but last to be separated with a ";\n" but format last one to be ...

66. What does "%1$#" mean when used in String.format (Java)?

Language is Java. What does the "%1$#" mean in...

static String padright (String str, int num) {
   return String.format("%1$#" + num + "str", str);
In the Java API, String.format is used in ...

67. String format using java

I have to make below statement as string.i am trying,but it's giving invalid character sequence.I know it is basic,But not able to do this.any help on this appreciated.

String str="_1";

'\str%' ESCAPE '\'

Output ...

68. idiomatic way to combine formatting and string appending?

Is there a better way to build strings with formatting and appending than this example? This is a Java question. Edit: It seems that it would be ...

69. Where's definitive reference on string formatting

does anyone know of a good online resource that simply and definitevly explains how to use the string formatter method...? I need to write a series of "records" into a set ...

70. how to format string in Java

Primitive question.. But how do I format string like this:

"Step {1} of {2}"
by substituting variables using Java? In C# it's easy.

71. Using String.format with RPGLE

I would like to interface RPGLE with String.format which takes variable length arguments or an array, I also want to pass numbers as well as strings, so I will be ...

72. String.format: 2 => 02

       String formatted = String.format("%d:%d", 2, 5);
I will output 2:5 But I want: 02:05, and I don't want extra zero for numbers > 9. In this ...

73. Java equivalent of: String.format("{0:D9}", Result);

Does anyone know the Java equivalent of the C# format of:

String.format("{0:D9}", Result);
Here what it does: This little problem is killin' me...

74. In Java, is the immutability of Strings considered in the implementation of String.format()?

Since Strings in Java are immutable, I've always used StringBuilder or StringBuffer to concatenate Strings. Does the String.format() method handle this issue as well as StringBuilder or StringBuffer? In ...

75. Java beginner question - String.format

When I call the displayTime12hrclock method in another class, it refuses to print out AM or PM. I can't work out why.

public class Tuna {

    private int hour;

76. How do I format a string with properties from a bean

I want to create a String using a format, replacing some tokens in the format with properties from a bean. Is there a library that supports this or am I going ...

77. Java format Number/Amount to

I would like to format an amount : the required format is : #.##0,00 example : 299.552.698,05 or 299.552.698,00 When I try to use

  (new DecimalFormat("#.##0,00")).format($F{amount}.doubleValue())
It causes an exception and ...

78. Format a String in C++ with the same convenience as String.format() in Java 5 / 6?

Is there a common function available to be able to do sprintf type String formatting without having to supply a fixed size buffer, that returns a string class instance? I know about ...

79. What about if you've got the same parameter multiple times in String.format?

String hello = "Hello";

String.format("%s %s %s %s %s %s", hello, hello, hello, hello, hello, hello);

hello hello hello hello hello hello 
Does the hello variable need to be repeated multiple times in ...

80. Java Formatter - what is '#' for?

According to javadoc, the '#' flag stands for "The result should use a conversion-dependent alternate form". I wasn't able to find any details on that. Could someone explain what ...

81. better alternative to message format

I have a string of following format

Select * where {{0} rdfs:label "Aruba" } limit 10
Now I would like to replace {0} with some new text, but the problem is message ...

82. convert EBCDIC String to ASCII format?

I am having a flat file which is pulled from a Db2 table ,the flat file contains records in both the char format as well as packed decimal to convert ...

83. Properly format a Java String to fit into a JavaScript variable

I'm pretty new to Java, let's say I have a String containing multiple things (quotes, double quotes, new lines etc...) I want to "encode" that string so I can output it safely ...

84. Convert String in html format to mailto link

In Java webapp, I need an automatic converter to convert String to use in a mailto link By example, I have this String "S&D" will be display in a html correctly "S&D". ...

85. Formatting string in Java using return string.format(...)

Say I want to return something like this: "Title bookTitle, Author bookAuthor: $cost" The ones in bold are variables. I can't figure out how to return this using string.format("%s .., blah blah")

86. Way to format strings with "?" parameters to full string in java?

For example I want to implement class with method

public class Logger {

    public void info(String message, String[] params) {
If input is
new Logger().info("Info: param1 ...

87. Quickest & most efficient way of formatting a String

What is the quickest way for converting a date which is a string with the format "20110913" to "2011-09-13" in Java.

88. Java String.Format() specifier 's' - strange behaviour

I have following code:

String requestString=String.format(Constants.SEARCH_SETS_API,

89. How to format Time and String value in Java's String formatter

Using Java String.format() how do I format a string to result in "Time - userId" (ie. 3:02 pm - joe user). I have worked several iterations, and I think it is the ...

90. Java safe String.format and escaping %

I'm using String.format method of Java API to log something. My method is like:

public static void log(String message, Object... params){
    System.out.println(String.format(message, params));
However the problem is, if the user ...

91. how to printf a long typed value using input size modifier?

This is basically what I am trying to do

// ... some code, calculations, what have you ...
long timeToAdd = returnTimeToAddInLongFormat();

// lets output the long type now, and yes i need the ...

92. Why does Java takes Input in String format only?

In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it ...

93. Is there a java library that supports smart parameter expansion, String.format, and more

Here's what I'm looking for:

  • Java
  • Log library that could replace commons logging or slf4j
  • Parameter expansion only when log level requires it (i.e. no if (log.isDebugEnabled()) blocks)
  • String formatting the same as java.lang.String.format
  • Detect java.lang.Throwable ...

94. This code should give output as the given format

This is code in java for string.

int a=6;
int b=7;

I want to comes the output is 6\7.

95. String.format() is not working?

Here is my code:

timeFormat = String.format("%02d:%02d:%02d",hoursFormat, minsFormat, secsFormat);
hoursFormat, minsFormat, and secsFormat are all ints This gives a compilation error:
Unresolved compilation problem: 
    The method format(String, Object[]) in the type ...

96. Java concatenate to build string or format

I'm writing a MUD (text based game) at the moment using java. One of the major aspects of a MUD is formatting strings and sending it back to the user. ...

97. Arbitrary radix padded format

I wonder if there's a standard way in Java to format an integer number into an arbitrary radix with left-padded zeroes. E.g. for radix-32, padded to 4 characters length, if I ...

98. format string java

I need to change a string from the following format "6254897283" to the following format " (625) 555-1212." Any ideas for the best way to do this? I will do it ...

99. Print out square format java

I need to print out a square of hashes in the following type of format: #### #### #### #### I ...

100. How to center a string using String.format?

public class Divers {
  public static void main(String args[]){

     String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
     System.out.format(format, "FirstName", "Init.", "LastName");
     System.out.format(format, ...  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.