iOS Objective-C 如何获得 2 个十进制四舍五入的浮点值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18063721/
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-08-31 00:36:41  来源:igfitidea点击:

iOS Objective-C How to get 2 decimal rounded float value?

iosobjective-cfloating-pointdecimalrounding

提问by B-Man

I have a

我有一个

float a = 1412.244019;

and I need a to be rounded to the nearest second decimal like 1412.24000000. I understand that if i want to present a with only two decimals i use %.2f, but that is NOT the case. I need the new a for mathematical reasons as a float.

我需要四舍五入到最接近的第二位小数,如 1412.24000000。我知道,如果我想显示只有两位小数的 a,我会使用 %.2f,但事实并非如此。出于数学原因,我需要新的 a 作为浮点数。

I have tried a couple of methods found on stackoverflow without luck. The more obvious one i used, i mention below, but still had no luck using it. Can YOU see why the magic is not happening?

我已经尝试了在 stackoverflow 上找到的几种方法,但没有运气。我使用的更明显的一个,我在下面提到,但仍然没有使用它。你能明白为什么魔法没有发生吗?

PS: It does do the desired effect sometimes, NOT always, which gets me thinking... hmmm...

PS:它有时确实会达到预期的效果,但并非总是如此,这让我想到......嗯......

Thanks in advance.

提前致谢。

Code:

代码:

float a = 1412.244019;
NSLog(@"a is %f", a); //output a is 1412.244019
a = [[NSString stringWithFormat:@"%.2f", a] floatValue];
NSLog(@"a is %f", a); //output a is 1412.239990

EDIT:

编辑:

SEEMS like when i am using the float a after the above surgery, it is considering it to be 1412.240000 eventhough the NSLog says differently... strange. But i am getting what I want, so Kudos for wasted time chasing nothing :)

似乎当我在上述手术后使用浮动 a 时,它认为它是 1412.240000,尽管 NSLog 说的不同......奇怪。但是我得到了我想要的东西,所以浪费时间什么都不做,我很荣幸:)

EDITI would love to choose you all as correct answers, but since i can only choose one, i chose the first good answer with extra explanation (of the two last).

编辑我很想选择你们所有人作为正确答案,但由于我只能选择一个,我选择了第一个带有额外解释的好答案(最后两个)。

回答by Lucas Eduardo

Have you tried this?

你试过这个吗?

CGFloat val = 37.777779;

CGFloat rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
CGFloat nearest = floorf(val * 100 + 0.5) / 100;  /* Result: 37.78 */
CGFloat rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

source : Rounding Number to 2 Decimal Places in C

来源:四舍五入到 C 中的 2 个小数位

Complementing: You just don't have control about how the computer will store the float value.

补充:您只是无法控制计算机将如何存储浮点值。

So these rounded values may not be EXACTLY the "obvious" decimal values, but they will be very very close, and that's the max guarantee you will have.

所以这些四舍五入的值可能不完全是“明显的”十进制值,但它们会非常接近,这是您将拥有的最大保证。

回答by gnasher729

You do that in Objective-C exactly the same as you would in C:

您在 Objective-C 中的做法与在 C 中的做法完全相同:

double notRounded = ...;
double rounded = round (notRounded * 100.0) / 100.0;

Don't use float - unless you can explain to someone exactly what your specific reasons are to use float over double. float has very limited precision. And using ceil or floor is daft, since there is a perfectly fine standard function named "round".

不要使用浮动 - 除非您可以向某人确切解释您使用浮动超过双倍的具体原因。float 的精度非常有限。使用 ceil 或 floor 是愚蠢的,因为有一个名为“round”的完美标准函数。

Neither float nor double can exactlyrepresent most decimal values, like 12.24. Because it has much higher precision, double will let you get much closer to 12.24. Therefore, there is a huge chance that NSLog will display some weird number for (float) 12.24, like 12.23999997394 or whatever, while it may display 12.24 for double.

float 和 double 都不能准确表示大多数十进制值,例如 12.24。因为它有更高的精度,double 会让你更接近 12.24。因此,NSLog 很有可能会为 (float) 12.24 显示一些奇怪的数字,例如 12.23999997394 或其他什么,而它可能会为 double 显示 12.24。

回答by Mitesh Varu

Error in this Line

此行中的错误

a = [[NSString stringWithFormat:@"%.2f", a] floatValue];

correct it to

改正为

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

回答by Eric Postpischil

The closest value to 1412.24 that a floatcan have is 1412.239990234375. There is nooperation that can produce a floatany closer than that, because the format of floatobjects does not represent any closer values. Asking to represent 1412.24 in floatis like asking to represent 2.5 in int. It simply cannot be done.

afloat可以拥有的最接近 1412.24 的值是 1412.239990234375。有没有操作,可以产生一个float比这更接近,因为格式float对象不代表任何更接近的值。要求代表 1412.24 infloat就像要求代表 2.5 in int。它根本无法做到。

Options for dealing with this include:

处理此问题的选项包括:

  • You can use use formatting that displays “1412.24”, without changing the underlying floatobject.
  • You can use doubleto get closer (much closer), but it will still not be exactly 1412.24.
  • You can scale floatvalues to representable values (e.g., measure in other units so that the values you want are all exactly representable in float).
  • You can use a different data type, such as NSDecimal.
  • 您可以使用显示“1412.24”的格式,而无需更改基础float对象。
  • 您可以使用double来接近(更接近),但它仍然不会正好是 1412.24。
  • 您可以float将值缩放为可表示的值(例如,以其他单位进行测量,以便您想要的所有值都可以在 中准确表示float)。
  • 您可以使用不同的数据类型,例如NSDecimal.

回答by David Elliman

You could multiply a by 100.0 and perhaps add 0.5 for rounding and then take the int value of the result. You can then use / 100 to get the value before the decimal point and % 100 to get the two decimal places.

您可以将 a 乘以 100.0 并可能添加 0.5 进行四舍五入,然后取结果的 int 值。然后,您可以使用 / 100 获得小数点前的值,使用 % 100 获得两位小数。

回答by Owen Hartnett

You can't force a float value. Floats are designed to be somewhat approximate, as their magnitude can be great, and since you've only got so many bits to use, it can get close to, but not exactly express a decimal number.

您不能强制使用浮点值。浮点数被设计为有点近似,因为它们的大小可能很大,而且由于您只有这么多位可以使用,它可以接近但不能完全表达十进制数。

One suggestion is to do all your arithmetic in integer, multiplied by 100, then dividing when you want to display your final result. You may have numbers too large which would prohibit this.

一个建议是用整数进行所有算术运算,乘以 100,然后在想要显示最终结果时进行除法。您可能有太大的数字,这会禁止这样做。