• 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
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

printf question

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Why does this print 7.00 and not 07.00 ?
 
Sheriff
Posts: 9697
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In 02.2, as you know 0 is for filling 0s when the number is less than the minimum size. 2.2 means that the minimum length of the number must be 2 (2.2) and there must be 2 digits after the decimal point (2.2). So here there is no restriction that there must be 2 digits before the decimal point. Try 04.2 to see the result...
 
ujjawal rohra
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Ankit
I am sorry i didnt understand.You are saying that 02 is for filling up the space with zeroes when the number is less
than 2 digits. It is 7 in this case which means it is smaller than 2 digits so it must be padded with 0s.
Also, 04.2 also prints 7.00.
Please clarify
 
Ankit Garg
Sheriff
Posts: 9697
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Also, 04.2 also prints 7.00.


Yes sorry I forgot about the decimal point. 05.2 will give you 07.00 output.

The thing is, when you say 03.2 (I'm using a different value to make it easier to understand), you are indicating that the number must span at least 3 digits. This includes the number before the decimal point, the decimal point itself and the numbers after the decimal point. Since we have 2 digits after the decimal point, so the length already is more than the minimum length of the number.

Lets say I write printf("%08.2f",new Double(7)), here I want to print the number 7 with 2 digits after the decimal point and I want it to span at least 8 digits. So the output will be 00007.00 which as you can see spans 8 digits...
reply
    Bookmark Topic Watch Topic
  • New Topic