xcode 字符串加倍
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7555187/
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
String to double
提问by Alex van Rijs
I hope you can help me out with this 'small' problem. I want to convert a string to a double/float.
我希望你能帮我解决这个“小”问题。我想将字符串转换为双精度/浮点数。
NSString *stringValue = @"1235";
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/(double)100.00];
I was hoping this to set the priceLabel to 12,35 but I get some weird long string meaning nothing to me.
我希望这可以将 priceLabel 设置为 12,35,但我得到了一些奇怪的长字符串,对我来说没有任何意义。
I have tried:
我试过了:
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue intValue]/(double)100.00];
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/100];
but all without success.
但都没有成功。
回答by Tendulkar
This is how to convert an NSString
to a double
这是如何将 an 转换NSString
为 adouble
double myDouble = [myString doubleValue];
回答by Vijay-Apple-Dev.blogspot.com
You have to use %f to show float/double value.
您必须使用 %f 来显示浮点/双精度值。
then %.2f means 2digits after dot
然后%.2f 表示点后的 2digits
NSString *stringValue = @"1235";
NSString *str = [NSString stringWithFormat:@"%.2f",[stringValue doubleValue]/(double)100.00];
NSLog(@"str : %@ \n\n",s);
priceLabel.text = str;
OUTPUT:
输出:
str : 12.35
字符串:12.35
回答by Stephen Darlington
I think you have the wrong format string. Where you have:
我认为你有错误的格式字符串。你有:
[NSString stringWithFormat:@"%d", ...];
You should really have:
你真的应该有:
[NSString stringWithFormat:@"%f", ...];
%d
is used for integer values. But you're trying to display a floating point number (%f
).
%d
用于整数值。但是您正在尝试显示一个浮点数 ( %f
)。