简体   繁体   中英

how to set precision in Objective-C

In C++, there is a std::setprecision function can set float/double precision. how can i set precision in 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? how can i get the result is 0.05?

Floating-point numbers are binary floating-point numbers. 0.05 cannot be represented exactly by a binary floating point number. The result cannot ever be exactly 0.05.

In addition, you are quite pointlessly using float instead of double. float has only six or seven digits precision. Unless you have a very good reason that you can explain, use double, which gives you about 15 digits of precision. You still won't be able to get 0.05 exactly, but the error will be much less.

You may use NSNumberFormatter to format objects in a wide variety of ways --- too numerous to list here, see the documentation available from Xcode. Also see the Data Formatting Guide.

You must make change between % modulo operator and its identifier f in order to get desired result.

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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