aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes format query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "format query" Watch "format query" New topic
Author

format query

gunjan khanuja
Ranch Hand

Joined: Apr 16, 2012
Posts: 37
public class ProjectNew
{


public static void main(String[] args)
{
double d = 12.345;


System.out.printf("|%7f| \n", d);


System.out.printf("%02.2f%s%b",new Double(7),"gg",false);
}
}

According to my understanding the output should be |12.3450| but after running the code i get |12.345000| .Please explain why is this so??
Also in the second statement how is false related to %b.when should i get true and when should i get false as the output.Please explain with example?
Md. Minhajur Rahman
Ranch Hand

Joined: Apr 10, 2012
Posts: 33
For float number, If the precision is not specified then the default value is 6. so the output is |12.345000|.
If the precision is specified, that is used. As your 2nd case, precision is 2. so output is 7.00ggfalse. false is printed as you pass false as argument. if you pass true, true will be printed.
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

you did not specify precision in your code:
you did "%7f"
so the following rule applies:
The number of digits in the result for the fractional part of m or a is equal to the precision. If the precision is not specified then the default value is 6. (from http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html)

if you specify precision:
%2.4f

you would get
12.3450


saying %b tells the formatter put a boolean there and you gave it false so it printed false as output. Instead of false you can give it any boolean expression and it will output it as your %b

for experiment, try


and

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: format query