• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

format query

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 820
IntelliJ IDE VI Editor Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic