• 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

String formatting question

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I found this in the JQPlus mock exam:

could you please explain to me why this piece of code:


changes the -2222 to -2,222? (or o be precise it prints out "-2,222")?

K & B book says the comma causes the usage of locale-specific grouping operators, but why is the comma added after the first 2?

Thanks,
Justyna
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not sure what your locale is, but I know in the US it's common to write a comma to seperate groups of three digits.
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My question is why do you have to use escape character when you can use like this,

System.out.printf("%,d",ii);



I believe by default it uses US locale unless you want to define locale using following method,

printf(Locale l,
String format,
Object... args)

 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Venkat Sidh:
My question is why do you have to use escape character...


In this example, double quotes are supposed to be part of the output, so the escape sequence is needed. These are not part of the format specifier, which is simply %,d . If you did not want the output to appear within double quotes, you would not need the escape sequences.
 
Venkat Sidh
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, I missed out that it is part of output.....I still need to improve to find these gotchas.
 
reply
    Bookmark Topic Watch Topic
  • New Topic