【问题标题】:String to double字符串加倍
【发布时间】:2011-09-26 12:38:50
【问题描述】:

我希望你能帮我解决这个“小”问题。我想将字符串转换为双精度/浮点数。

NSString *stringValue = @"1235";
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/(double)100.00];

我希望这可以将 priceLabel 设置为 12,35,但我得到了一些奇怪的长字符串,对我来说毫无意义。

我试过了:

priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue intValue]/(double)100.00];

priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/100];

但都没有成功。

【问题讨论】:

标签: iphone objective-c xcode double


【解决方案1】:

这是将NSString 转换为double 的方法

double myDouble = [myString doubleValue];

【讨论】:

  • 这么奇怪的问题是字符串加倍。接受的答案甚至不能解决这个问题。但是这里有这个。 :) 谢谢
【解决方案2】:

你必须使用 %f 来显示浮点/双精度值。

然后%.2f 表示点后2位

NSString *stringValue = @"1235";

NSString *str = [NSString stringWithFormat:@"%.2f",[stringValue doubleValue]/(double)100.00];

NSLog(@"str : %@ \n\n",s);

priceLabel.text = str;

输出:

str : 12.35

【讨论】:

【解决方案3】:

我认为你的格式字符串有误。你在哪里:

[NSString stringWithFormat:@"%d", ...];

你真的应该有:

[NSString stringWithFormat:@"%f", ...];

%d 用于整数值。但是您正试图显示一个浮点数 (%f)。

【讨论】:

    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多