Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 613 Vote(s) - 3.44 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Make a float only show two decimal places

#11
It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

E.g.:

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 `0`s.

E.g.:

%f = 25.000000
%.f = 25
%.02f = 25.00
Reply

#12
Use `NSNumberFormatter` with `maximumFractionDigits` as below:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);

And you will get `12.35`
Reply

#13
The problem with all the answers is that multiplying and then dividing results in precision issues because you used division. I learned this long ago from programming on a PDP8.
The way to resolve this is:

return roundf(number * 100) * .01;

Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.

What level of precision you want is up to you. Just don't divide the product, multiply it by the decimal equivalent.
No funny String conversion required.
Reply

#14
Here are few corrections-

//for 3145.559706

---

**Swift 3**

let num: CGFloat = 3145.559706
print(String(format: "%f", num)) = 3145.559706
print(String(format: "%.f", num)) = 3145
print(String(format: "%.1f", num)) = 3145.6
print(String(format: "%.2f", num)) = 3145.56
print(String(format: "%.02f", num)) = 3145.56 // which is equal to @"%.2f"
print(String(format: "%.3f", num)) = 3145.560
print(String(format: "%.03f", num)) = 3145.560 // which is equal to @"%.3f"

---
**Obj-C**

@"%f" = 3145.559706
@"%.f" = 3146
@"%.1f" = 3145.6
@"%.2f" = 3145.56
@"%.02f" = 3145.56 // which is equal to @"%.2f"
@"%.3f" = 3145.560
@"%.03f" = 3145.560 // which is equal to @"%.3f"

and so on...
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through