gpt4 book ai didi

objective-c - NSNumberFormatter 转换删除小值的小数

转载 作者:行者123 更新时间:2023-12-03 17:23:11 25 4
gpt4 key购买 nike

我们的质量保证团队发现了缺陷。当他们在货币字段中写入 0.0950,095 时,NSNumberFormatter 会将内容转换为 95

这是我们正在使用的代码:

+ (NSNumber *) getNumberWithDecimalFromString:(NSString*) theSource
{
if ([TSCommons isEmpty:theSource])
return [[NSNumber alloc] initWithInt:0];

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

if ([theSource rangeOfString:@","].location != NSNotFound) {
[formatter setDecimalSeparator:@","];
[formatter setCurrencyDecimalSeparator:@"."];
} else if ([theSource rangeOfString:@"."].location != NSNotFound) {
[formatter setDecimalSeparator:@"."];
[formatter setCurrencyDecimalSeparator:@"."];
}
NSNumber *tmp = [formatter numberFromString:theSource];

[formatter release];
return [tmp retain];
}

区域设置为es_ES

对这种意外行为有什么想法吗?

为了介绍这个问题的更多信息,因为上次XCode更新后又回来我准备了一个测试

- (void) testNumberFormatter
{
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,1"] doubleValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,12342"] doubleValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,12"] floatValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,123"] floatValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,1234"] floatValue]);
NSLog(@"%f",[[TSCommons getNumberWithDecimalFromString:@"41,1234234"] doubleValue]);
}

控制台上的结果如下:

41.100000

41.123420

41.119999

41123.000000

41.123402

41.123423

谢谢!!

最佳答案

 NSString* theSource = @"0.095";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

if ([theSource rangeOfString:@","].location != NSNotFound) {
[formatter setDecimalSeparator:@","];
[formatter setCurrencyDecimalSeparator:@"."];
} else if ([theSource rangeOfString:@"."].location != NSNotFound) {
[formatter setDecimalSeparator:@"."];
[formatter setCurrencyDecimalSeparator:@"."];
}
NSNumber *tmp = [formatter numberFromString:theSource];
NSLog(@"get Number %@ - %lf %lf", tmp, [theSource doubleValue], [tmp floatValue]);

//输出获取数字0.095 - 0.095000 0.095000

关于objective-c - NSNumberFormatter 转换删除小值的小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15139600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com