xcode 如何将类型 double 转换为字符串 iPhone?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6687239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:28:41  来源:igfitidea点击:

How to convert type double to string iPhone?

iphonexcodensstringdoublevelocity

提问by Dietrich Epp

I am calculating the velocity of an iPhone, and I need to know how to convert the variable calculatedSpeed which is type double to type string to display on a label.

我正在计算 iPhone 的速度,我需要知道如何将 double 类型的变量 calculateSpeed 转换为类型字符串以显示在标签上。

Here is what I have in the header:

这是我在标题中的内容:

@interface myProject : UIViewController <CLLocationManagerDelegate> {

double calculatedSpeed; 
    UILabel *velocityLabel;
}

And here is what I have in the main:

这是我的主要内容:

-(void)speedLocation:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
double gpsSpeed = newLocation.speed;

if(oldLocation != nil)
{
    CLLocationDistance distanceChange = [newLocation getDistanceFrom:oldLocation];
    NSTimeInterval sinceLastUpdate = [newLocation.timestamp timeIntervalSinceDate:oldLocation.timestamp];
    calculatedSpeed = distanceChange / sinceLastUpdate;

    velocityLabel.text = calculatedSpeed;

}

}

Notice how I am trying to set velocityLabel to calculatedSpeed, which is a variable with the type double. So it naturally gives me the error: incompatible type for argument 1 of 'setText:'.

请注意我如何尝试将velocityLabel 设置为calculatedSpeed,这是一个double 类型的变量。所以它自然给了我错误:'setText:' 的参数 1 的类型不兼容。

Your help is greatly appreciated.

非常感谢您的帮助。

Thanks!

谢谢!

回答by Dietrich Epp

velocityLabel.text = [NSString stringWithFormat:@"%g", calculatedSpeed];