在使用文化信息时,将数字转换为double时,我遇到了奇怪的行为
使用荷兰文化转换- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"cellID";
RACollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
[cell.imageView removeFromSuperview];
cell.imageView.frame = cell.bounds;
cell.imageView.image = [UIImage imageNamed:[_photosArray objectAtIndex:indexPath.item]];
cell.backgroundColor = [UIColor lightGrayColor];
[cell.contentView addSubview:cell.imageView];
UIButton *addBtn =[[UIButton alloc]init];
addBtn.tag=indexPath.row;
deleteBtn.frame = CGRectMake(100, 100, 19, 19);
UIImage *img=[UIImage imageNamed:@"ic_add_photo.png"];
[addBtn setImage:img forState:UIControlStateNormal];
[addBtn addTarget:self action:@selector(addBtnAction) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:addBtn];
return cell;
}
-(void)addBtnAction
{
UIAlertController *actionsheetController = [[UIAlertController alloc]init];
UIAlertAction *library = [UIAlertAction actionWithTitle:@"Choose from Library" style:UIAlertActionStyleDefault handler:^(UIAlertAction
* action)
{
// Library button tapped
[self performSelector:@selector(libraryBtnAction) withObject:nil];
}];
[actionsheetController addAction:library];
actionsheetController.view.tintColor = [UIColor darkGrayColor];
[self presentViewController:actionsheetController animated:YES completion:nil];
}
-(void)libraryBtnAction
{
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
chosenImage = info[UIImagePickerControllerEditedImage];
cell.imageView.image = chosenImage;
[_collectionView reloadData];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
时,处理正确。如果我使用美国文化转换"3,3"
,则返回"3,3"
。我期待一个错误。看我的例子:
33
处理此问题的正确方法是什么?当小数(或千位)分隔符无效时,我更喜欢异常。
答案 0 :(得分:2)
如果您只想解析它,我会使用专用的解析方法,您可以在其中设置Numberstyles
以下代码将抛出FormatException
var culture =new CultureInfo("en-US");
var result = double.Parse("3,3", NumberStyles.AllowDecimalPoint, culture);
有关详细信息,请参阅Double.Parse Method
答案 1 :(得分:0)
与Boas Enkler的回答一起,我已经能够解决问题了。因此,首先,我将根据当前的文化扫描千位分隔符的输入。最后我将输入值解析为double。
private static string RemoveThousandSeparator(string input)
{
Regex removeThousandSeparatorExpr = new Regex(@"^-?(?:\d+|\d{1,3}(?:\"
+ <CultureInfo>.NumberGroupSeparator + @"\d{3})+)(?:\"
+ <CultureInfo>.NumberDecimalSeparator + @"\d+)?$");
Match match = removeThousandSeparatorExpr.Match(input);
if (match.Success)
{
input = input.Replace(<CultureInfo>.NumberGroupSeparator, "");
}
else
{
throw new Exception("Invalid input value");
}
return input;
}