使用逗号时将String转换为double [英] Convert String to double when comma is used

查看:62
本文介绍了使用逗号时将String转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITextfield,它正被数据库中的数据填充.该值的格式设置为小数部分用逗号分隔.因此,结构类似于1,250.50

I have a UITextfield and it is being populated by data from database. The value is formatted in a way that the fractional part is separated by comma. So, the Structure is something like 1,250.50

我将数据保存在字符串中,当我尝试使用doubleValue方法将字符串转换为双精度或浮点数时.我得到1.这是我的代码.

I save the data in a string and when I try to use the doubleValue method to convert the string to a double or floating number. I am getting 1. Here is my code.

NSString *price = self.priceField.text; //here price = 1,250.50
double priceInDouble = [price doubleValue];

在这里我得到1而不是1250.50.

Here I get 1 instead of 1250.50.

我想,问题是逗号,但是我无法摆脱这个逗号,因为它来自数据库.谁能帮助我将此字符串格式转换为double或float.

I guess, the issue is the comma, but I can't get rid of that comma as it is coming from the database. Can anyone please help me to convert this string format to double or float.

推荐答案

此解决方案实际上是删除逗号.尽管您最初是从数据库中获得这些逗号的,但是您可以在转换之前将其删除.添加它作为从数据库获取数据并将其转换为双精度之间的附加步骤:

The solution on this really is to remove the commas. Although you are originally getting those commas from the database, you can just remove them before conversion. Add it as an additional step in between getting the data from the DB and converting it to a double:

NSString *price = self.priceField.text;  //price is @"1,250.50"
NSString *priceWithoutCommas = [price stringByReplacingOccurrencesOfString:@"," withString:@""];  //price is @"1250.50"
double priceInDouble = [priceWithoutCommas doubleValue]; //price is 1250.50

这篇关于使用逗号时将String转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆