开发者

What is wrong with this string format (different behavior on simulator and device)?

开发者 https://www.devze.com 2023-01-21 21:51 出处:网络
I have this block of code executed when pressing a number: NSString *currentValue = [@\"\" stringByAppendingFormat:@\"%.02f\", [[[[[textField text] stringByReplacingOccurrencesOfString:@\".\" withStr

I have this block of code executed when pressing a number:

    NSString *currentValue = [@"" stringByAppendingFormat:@"%.02f", [[[[[textField text] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] doubleValue]/100.0f];
            //I am using this to obtain always a number with 2 decimals.

    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    [f setMinimumFractionDigits:2];
    [f setMaximumFractionDigits:2];
    [f setGroupingSeparator:@" "];

    NSNumber *currentNumberValue = [f numberFromString:currentValue];
    NSLog(@"1: %@", currentValue);
    NSLog(@"2: %@", [currentNumberValue stringValue]);

Now if I run this in the simulator and press 3 I get the following results:

1: 0.03
2: 0.03

If I run it on the device I have:

1: 0.03
2: 0

So basically on the device the formated number is 0.

What I have also noticed is that on the simulator I get '.' as a decimal separator and on the device I have ','.

And because of this it never gets further. Any number I press it开发者_JS百科 still remains 0.

What seems to be the problem?


Your device is apparently set to a European (or wherever) locale that uses , as the decimal separator. Try adding this line after the line where you alloc and init your number formatter:

[f setDecimalSeparator:@"."];

Or use the setLocale method (or change the locale your device is set to).


Try it like this:

NSString *currentValue = [textField text];
float currentFloat = [currentValue floatValue];
NSLog(@"%.2f",currentFloat); //string representation of floatValue
NSLog(@"%@",currentValue); //string currentValue
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号