将NSString解析为Double [英] parsing NSString to Double

查看:118
本文介绍了将NSString解析为Double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想将NSString转换为两倍.我发现以下示例:

so I want to convert NSString to double. I found the following example:

NSString * s = @"1.5e5";
NSLog(@"%lf", [s doubleValue]);

它可以工作,但是如果doubleValue无法将字符串转换为两倍,它只会返回0.0,这不是我所需要的.我需要一些方法来尝试将字符串表示形式的double转换为double,并在无法转换的情况下通过某种方式进行指示. c#具有出色的方法

It works but if doubleValue cannot convert the string to double it simply returns 0.0 which is not what I need. I need some method that tries to convert a string representation of double to double and if indicate somehow if it can't be converted. c# has an excellent method

double d;
boolean Double.TryParse(str, out d)

是否有与目标C中的上述方法类似的方法?还是最好使用正则表达式?但是,我真的不知道该怎么做.

Is there any method similar to the above one in Objective C? or maybe it's better to use regex? however, i don't really know how to do that.

推荐答案

您可以使用NSScanner类:

NSString *s = @"1.5e5";
NSScanner *scanner = [NSScanner scannerWithString:s];
double d;
BOOL success = [scanner scanDouble:&d];

如果要确保已扫描整个字符串(数字后没有多余的字符),请使用

If you want to ensure that the entire string has been scanned (no extra characters after the number), use

BOOL isAtEnd = [scanner isAtEnd];

这篇关于将NSString解析为Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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