7

I have some code to format a file size string:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
[numberFormatter setPositiveFormat: @"#,##0.## bytes"];

Is the @"#,##0.## bytes" the same kind of format string as I'd use in stringWithFormat? What do the hash/pound symbols mean here?

4 Answers 4

14

# will usually be replaced by a number if one exists, and nothing if it doesn't. 0 will be replaced by a number if one exists, and zero if it does not.

So for the following formatting '##00.00##' you would get the following outputs:

1 => 01.00
12.1 => 12.10
1234.5 => 1234.50
1.2345 => 01.2345
1
  • Great, thanks for the examples, they cleared things up for me.
    – nevan king
    Jun 11, 2009 at 9:38
4

They are called placeholders.

Placeholders

You use the pound sign character (#) to represent numeric characters that will be input by the user. For example, for the positive pattern "$#,##0.00", if the characters 76329 were entered into a cell to which the pattern has been applied, they would be displayed as $76,329.00. Strictly speaking, however, you don't need to use placeholders. The format strings ",0.00", "#,#0.00", and "#,##0.00" are functionally equivalent. In other words, including separator characters in a pattern string signals NSNumberFormatter to use the separators, regardless of whether you use (or where you put) placeholders. The placeholder character's chief virtue lies in its ability to make pattern strings more human-readable, which is especially useful for displaying patterns in the user interface.

Source: http://developer.apple.com/documentation/InternetWeb/Reference/WO542Reference/com/webobjects/foundation/NSNumberFormatter.html

3

'#' represents an optional digit place that will not appear in case of a 0 digit in that position, whereas 0 means the digit will always appear.

Let's take 345.5 as an example:

#,##0.## = 345.5
0,000.00 = 0,345.50
2

'#' is in most languages used as an optional digit, as opposed to '0', which is a mandatory digit (to be used to get leading/trailing zeroes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.