how to get String with two decimal places in iphone app

后端 未结 1 910
夕颜
夕颜 2021-01-24 03:41

I have app in which i have method which inserts comma in NSString in thousands values i also want to include decimall like if i enter now 1000 then it shows 1,000 using this met

相关标签:
1条回答
  • 2021-01-24 03:44

    Why reinvent the wheel? Just use an NSNumberFormatter.

    double someNumber = 1000.0;
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    // Use decimal style - this includes grouping
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    // Force two decimal places
    [formatter setMinimumFractionDigits:2];
    [formatter setMsximumFractionDigits:2];
    
    NSString *formattedNumber = [formatter stringFromNumber:@(someNumber)];
    

    This also has the advantage that it will format the number properly based on the user's locale.

    It will appears as 1,000.00 or 1.000,00 or 1 000,00 or some other proper format for the user.

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