Pregunta

I have a string that represents a float, for example 2400.0. I want to format it as digit (2,400.0) and I need to keep the zero after the digit symbol.

NSString* theString = @"2400.0"; 

// I convert the string to a float 
float f = [theString floatValue]; 
// here I lose the digit information :( and it ends up with 2400 instead of 2400.0

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesSignificantDigits:YES];
[formatter setMinimumFractionDigits:1];
[formatter setMaximumFractionDigits:2];
[formatter setLocale:[NSLocale currentLocale]];

NSString *result = [formatter stringFromNumber:@(f)];

The NSLog of result is 2,400 while I need 2,400.0

How can I obtain the right string?

¿Fue útil?

Solución

You probably want to set the minimumFractionDigits to 1 (and your maximumFractionDigits as well in this case).

You also probably don't want to use significant digits. The following code yields the desired output:

NSString *theString = @"2400.0";

float f = [theString floatValue];

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:1];
[formatter setMaximumFractionDigits:1];
[formatter setLocale:[NSLocale currentLocale]];

NSLog(@"%@", [formatter stringFromNumber:@(f)]);

Otros consejos

Te below solves the issue

NSString *formatString = @"0,000.0";
[formatter setPositiveFormat:formatString];

The number of 0's after decimal will be used for formatting. It works for negative numbers also.

you should dynamically change the format string based on number of digits of the float value before and after decimal point.

Hope it helps.

easy,

then you go to display it just do this:

myLabel.text = @"%0.1f", f;

Use minimumFractionDigits in addition to maximumFractionDigits:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.minimumFractionDigits = 1;
formatter.maximumFractionDigits = 1;

XCTAssert([[formatter stringFromNumber:@(2400.0)] isEqualToString:@"2400.0"]);
XCTAssert([[formatter stringFromNumber:@(2400.1)] isEqualToString:@"2400.1"]);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top