Domanda

how to add commas in floating point number. means if i have number like 3652 than output will be 3,652.00 and if the number will be 3652.359618 than 3,652.36 it's work but for 3652 its not return two decimal points like 3,652.00 i am using now this code to do that :

float num = 3652;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; 
NSString *newString =  [formatter stringFromNumber:[NSNumber numberWithFloat:num]];
È stato utile?

Soluzione

You need to round the float number to make it rounded up to 2 decimal digits as shown below :

float num = 3652.359618; 
num = ceilf(num * 100) / 100;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSString *newString =  [formatter stringFromNumber:[NSNumber numberWithFloat:num]];

NSRange range= [newString rangeOfString:@"."];
if ( !range.length) {
    newString = [NSString stringWithFormat:@"%@.00",newString];
}

NSLog(@"%@",newString);

The following code works but not sure if this is a good way to achieve. I hope I will get comments/feedback on this. Other better answers are still welcome.

Altri suggerimenti

You should try below code:

NSString *newString =  [formatter stringFromNumber:[NSNumber numberWithFloat:(num*100.0)/100.0]];

NSNumberFormatterDecimalStyle uses device locale for displaying the numbers and separators. In order to enforce your own formatting, try setting the separators on the NSNumberFormatter:

[formatter setDecimalSeparator:@"."];
[formatter setThousandsSeparator:@","];

With that clarification on the goal, just add:

    [formatter setMinimumFractionDigits:2];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top