Change NSNumberFormatter's negative format from (xxx.xx) to -xxx.xx

前端 未结 4 1941
栀梦
栀梦 2021-01-02 14:25

I want to change my NSNumberformatter from displaying negative numbers with parenthesis around them to putting the minus sign in front (or whatever the localized standard is

相关标签:
4条回答
  • 2021-01-02 14:40

    If you take a look at the "Format Strings" section in the Data Formatting Programming Guide For Cocoa:

    The format string uses the format patterns from the Unicode Technical Standard #35 (this reference is to version tr35-6; formatters for Mac OS X v10.4 use version tr35-4).

    Edit:

    If you want to set a format string based on currencies, you can use the ¤ character, for example:

    [formatter setFormat:@"¤#,##0.00"];
    

    This will add the currency symbol for the current localization in place of the ¤ character.

    Therefore, applying the same concept to the negative format string:

    [formatter setFormat:@"-¤#,##0.00"];
    

    This will also apply the currency symbol in place of the ¤ for the current localization.

    0 讨论(0)
  • 2021-01-02 14:52

    In this case it is looking for a format NSString. Look here for format string details.

    If you want the negative of 12,345.67 to display as -12,345.67, then I believe the correct NSString value is @"-#,##0.00"

    I also noted the following sentence in the document linked above:

    If you don’t specify a format for negative values, the format specified for positive values is used, preceded by a minus sign (-).

    EDIT:
    Update for 10.4 and after: Here is a PDF describing behavior in 10.4 and after
    And, as linked from that document, here is the data on the required format for 10.4 and after.
    From this document, it appears the correct string may be: @"-#,##0.##"

    0 讨论(0)
  • 2021-01-02 15:01

    All of the answers given assume that the currency is to two decimal places and also uses commas as thousand separators. Obviously there are a number of currencies that don't conform to this standard, http://en.wikipedia.org/wiki/Decimal_mark, so I use the following technique

        NSString * formattedBalance = [currencyFormatter stringFromNumber:balance];
        if([formattedBalance rangeOfString:@"("].location != NSNotFound ) {
            formattedBalance = [NSString stringWithFormat:@"-%@",[[formattedBalance stringByReplacingOccurrencesOfString:@")" withString:@"" ]stringByReplacingOccurrencesOfString:@"(" withString:@"" ]];
        }
    
    0 讨论(0)
  • 2021-01-02 15:05

    OK, so the answer that I got working is:

    [currencyFormatter setNegativeFormat:@"-¤#,##0.00"];
    

    the key is this whatzit? character "¤". No idea what it's called? anyone? but it represents the localized currency in these format strings...

    0 讨论(0)
提交回复
热议问题