xcode 如何在目标 C 中将浮点数格式化为 2 位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2734412/
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
How to format float to 2 decimals in objective C
提问by Raphael Caixeta
I have a string that I'm converting to a float that I want to check for values in an if statement.
我有一个要转换为浮点数的字符串,我想检查 if 语句中的值。
The original float value is the iPhone's trueHeading that is returned from the didUpdateHeading method. When I convert the original float to a string using @"%.2f" it works perfectly, but what I'm trying to do is convert the original float number to the same value. IF I just convert the string to [string floatValue] I get the same original float number, and I don't want that.
原始浮点值是从 didUpdateHeading 方法返回的 iPhone 的 trueHeading。当我使用 @"%.2f" 将原始浮点数转换为字符串时,它工作得很好,但我要做的是将原始浮点数转换为相同的值。如果我只是将字符串转换为 [string floatValue],我会得到相同的原始浮点数,但我不想要那样。
To make it short and simple, how do I take an existing float value and just get the first 2 decimals?
为了简单起见,我如何获取现有的浮点值并只获取前 2 位小数?
回答by drawnonward
round( x * 100.0 ) / 100.0;
回答by ohho
float x = 123.45678;
int x1 = x * 100.0;
float x2 = (float) x1 / 100.0;
or if one-liner preferred
或者如果首选单线
float x3 = (float) ((int) (x * 100.0)) / 100.0;