NSString浮动...如果NSString不是数字并包含字母数字字符会发生什么? [英] NSString to float...what happens if NSString is not numerical and contains alphanumeric characters?

查看:171
本文介绍了NSString浮动...如果NSString不是数字并包含字母数字字符会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果
NSString sample = @1sa34hjh#@;

Float 64 floatsample = [sample floatValue];



会发生什么? floatsample包含什么?

解决方案

阅读 documentation

返回值

接收者文本的浮点值作为一个浮点数,跳过字符串开头的空格。溢出时返回HUGE_VAL或-HUGE_VAL,下溢时返回0.0。如果接收方不是以开头的有效文本表示形式,则返回 0.0 点数。



找出返回值的最好方法是自己检查返回值。您可以创建一个小程序并将其另存为扩展名为.m的文件。下面是一个例子:

$ pre $ lt; code> // floatTest.m
#import< Foundation / Foundation.h>

int main(){
NSString * sample = @1sa34hjh#@;
float floatsample = [sample floatValue];
printf(%f,floatsample);
返回0;



$ b $ p
$ b

使用clang在命令行上编译并连接到Foundation框架。

  clang floatTest.m -framework foundation -o floatTest 

$ $ $ $ $ $ $ $ $ $ $ $ $ $。$ float $ $

打印的值是 1.000000 。所以要回答你的问题,如果字符串以一个数字开始,那么字符串的数字部分将被采用并转换为浮点数。如果创建文件看起来像一个麻烦,你可能喜欢这篇博客文章 cocoawithlove.com/2010/09/minimalist-cocoa-programming.htmlrel =nofollow>简约的可可编程

if NSString sample = @"1sa34hjh#@";
Float 64 floatsample = [sample floatValue];

what happens? what does floatsample contain?

解决方案

Read the documentation.

Return Value

The floating-point value of the receiver’s text as a float, skipping whitespace at the beginning of the string. Returns HUGE_VAL or –HUGE_VAL on overflow, 0.0 on underflow.

Also returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.

The best way to figure out the return value is to check the return value yourself. You can create a small program and save it as a file with a .m extension. Here's a sample:

// floatTest.m
#import <Foundation/Foundation.h>

int main() {
    NSString *sample = @"1sa34hjh#@";
    float floatsample = [sample floatValue];
    printf("%f", floatsample);
    return 0;
}

Compile it on the command-line using clang and linking with the Foundation framework.

clang floatTest.m -framework foundation -o floatTest

Then run the executable and see the output.

./floatTest

The printed value is 1.000000. So to answer your question, if the string starts with a number, then the number portion of the string will be taken and converted to float. Same rules as above apply on overflow or underflow.

If creating the files seems like a hassle, you might like this blog post on minimalist Cocoa programming.

这篇关于NSString浮动...如果NSString不是数字并包含字母数字字符会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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