简体   繁体   English

如何在Objective-C中设置精度

[英]how to set precision in Objective-C

In C++, there is a std::setprecision function can set float/double precision.在 C++ 中,有一个 std::setprecision 函数可以设置浮点/双精度。 how can i set precision in Objective-C?如何在 Objective-C 中设置精度? and this print below:和下面的打印:

(lldb) p 10/200
(int) $0 = 0
(lldb) p (float)10/200
(float) $1 = 0.0500000007

line 3 result is 0.0500000007, why is '7' in the result?第 3 行的结果是 0.0500000007,为什么结果中是 '7'? how can i get the result is 0.05?我怎样才能得到结果是 0.05?

Floating-point numbers are binary floating-point numbers.浮点数是二进制浮点数。 0.05 cannot be represented exactly by a binary floating point number. 0.05 不能用二进制浮点数精确表示。 The result cannot ever be exactly 0.05.结果永远不可能是 0.05。

In addition, you are quite pointlessly using float instead of double.此外,您使用 float 而不是 double 是毫无意义的。 float has only six or seven digits precision. float 只有六或七位精度。 Unless you have a very good reason that you can explain, use double, which gives you about 15 digits of precision.除非你有一个很好的理由可以解释,否则使用 double,它给你大约 15 位的精度。 You still won't be able to get 0.05 exactly, but the error will be much less.您仍然无法准确地获得 0.05,但误差会小得多。

You may use NSNumberFormatter to format objects in a wide variety of ways --- too numerous to list here, see the documentation available from Xcode.您可以使用 NSNumberFormatter 以多种方式格式化对象 --- 太多无法在此列出,请参阅 Xcode 提供的文档。 Also see the Data Formatting Guide.另请参阅数据格式指南。

You must make change between % modulo operator and its identifier f in order to get desired result.您必须在% modulo运算符及其identifier f之间进行更改才能获得所需的结果。

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s. %.02f 告诉格式化程序您将格式化一个浮点数 (%f),并且应该四舍五入到两个位置,并且应该用 0 填充。

Example:例子:

%f = 25.000000    // results 25.000000 
%.f = 25    // results 25
%.02f = 25.00 // results 25.00

plz use请使用

     double A =  0.0500000007;
       NSString *b =[NSString stringWithFormat:@"$%.02f",A] ;
   double B = [b doubleValue];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM